淺談Vue中的this.$store.state.xx.xx
目錄
- this.$store.state.xx.xx
- 獲取store中的資料
- 我的專案檔案結構
- vue專案都在什麼時候用store.state、$store.state和this.$store.s
- store 和 [this.]$store
- this.$store 和 $store
Vue this.$store.state.xx.xx
this.$store.state.xx.xx 其實是Vue用到狀態管理工具Vuex
Vuex官網:https://vuex.vue.org/zh/
感覺就是把元件的共享狀態抽取出來,以一個全域性單例模式管理。在這種模式下,我們的元件樹構成了一個巨大的“檢視”,不管在樹的哪個位置,任何元件都能獲取狀態或者http://www.cppcns.com
獲取store中的資料
在vue根檔案中註冊store,這樣所有的元件都可以使用store中的資料了
我的專案檔案結構
在main.js檔案中註冊store
然後程式碼中寫到
登入後前端有快取userId,然後通過userId再去查詢
這個位子就用到了 公共頁面裡面的
總結:main.js是工會老大,你把獎勵給了老大,老大有的道具會交給你使用,那麼你就可以通過this來使用http://www.cppcns.com。
vue專案都在什麼時候用store.state、$store.state和this.$store.s
store 和 [this.]$store
簡單來說,如果你在根元件下注入了store那麼所有的.vue檔案裡使用就可以直接用 this.$store.xxxx
Vue官網:為了在 Vue 元件中訪問 this.$store.property,你需要為 Vue 例項提供建立好的 store。Vuex 提供了一個從根元件向所有子元件,以 store 選項的方式“注入”該 store 的機制
//main.js
import store from './store'
new Vue({
el: '#app',www.cppcns.com
store,//根元件注入store
})
//index.vue getData() { return { userId: this.$store.state.user.userId,...... } }
而在js檔案裡面如果想要使用store,就必須先引入import store from '@/store'然後使用store.xxx,因為js裡面是打印不出來this.$store的
// src/test.js檔案 import store from './store/'; console.log(store) console.log(this) // undefined console.log(this.$store) // 會報錯
this.$store 和 $store
$store 是掛載在 Vue 例項上的(即Vue.prototype),而元件也其實是一個Vue例項,在元件中可使用this訪問原型上的屬性
<template> 擁有元件例項的上下文,可直接通過 {{$store.state.XXX }} 訪問,等價於 script 中的 this.$store.state.XXX
就把 $store 看成在data中return的某個變數,在下面的script中使用需要加this,在上面的template中不需要加this
以上為個人經驗,希望能給大家一個參考,也希望大家多多支援我們。