vuex state及mapState的基礎用法詳解


  • 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> 

 

參考鏈接https://www.jb51.net/article/138460.htm


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM