vuex state及mapState的基礎用法詳解
阿新 • • 發佈:2020-10-25
- store.js檔案,這裡的store就是我們的前端資料倉庫,用vuex 進行狀態管理,store 是vuex的核心。
- 可以看到使用vuex 之前,要告訴 vue 使用它,Vue.use(Vuex);
/*store.js*/
let store= new Vuex.Store({
state: {
token:'',
//取出cartarry中的資料,或者為空
cartarry:JSON.parse(localStorage.getItem('cartarry')) || [],//儲存購物車商品的陣列
},
1, vue 提供了注入機制,就是把我們的store 物件注入到根例項中。vue的根例項就是 new Vue 建構函式,然後在所有的子元件中,this.$store 來指向store 物件。在store.js 中,我們let store, 把store已經暴露出去了,new Vue() 在main.js中,所以直接在main.js 中引入store 並注入即可。
/*main.js*/
import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'
Vue.config.productionTip = false
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
2, 在子元件中,用computed 屬性, computed 屬性是根據它的依賴自動更新的。所以只要store中的state 發生變化,它就會自動變化。在Cart.vue 中作下面的更改, 子元件中 this.$store 就是指向store 物件。我們把 store.js 裡面的token 變為8, 頁面中就變為了8。
export default {
computed: {
count () {
return this.$store.state.count
}
}
}
3, 通過computed屬性可以獲取到狀態值,但是元件中每一個屬性(如:count)都是函式,如果有10個,那麼就要寫10個函式,且重複寫10遍return this.$store.state,不是很方便。vue 提供了 mapState 函式,它把state 直接對映到我們的元件中。
當然使用mapState 之前要先引入它。它兩種用法,或接受一個物件,或接受一個數組。還是在display.vue 元件下。
物件用法如下:
<script>
import {mapState} from "vuex"; // 引入mapState
export default {
// 下面這兩種寫法都可以
computed: mapState({
count: state => state.count // 元件內的每一個屬性函式都會獲得一個預設引數state, 然後通過state 直接獲取它的屬性更簡潔
count: 'count' // 'count' 直接對映到state 物件中的count, 它相當於 this.$store.state.count,
})
}
</script>
陣列的方法如下:
<script>
import {mapState} from "vuex";
export default {
computed: mapState([ // 陣列
"count"
])
}
</script>