這里總結了幾個獲取vuex中數據的方法,如下代碼
store下的index.js存儲vuex數據
import Vue from "vue"; import Vuex from "vuex"; Vue.use(Vuex); const vuexLocal = new VuexPersistence({ storage: window.localStorage, }); export default new Vuex.Store({ state: { count:20 }, plugins: [vuexLocal.plugin], });
在vue中獲取count數據
1 import {mapState } from "vuex"; 2 export default { 3 methods:{ 4 submit2(){ 5 console.log(this.$store.state.count,"===");//方法1 6 console.log(this.count,"count") 7 } 8 }, 9 computed: { 10 ...mapState({count:'count'}),//方法2 11 }, 12 computed: mapState({ 13 count: 'count', //方法3 14 count: (Store) => Store.count, // 方法4 15 count: function (Store) { // 方法5 16 return '123:' + Store.count 17 }, 18 }), 19 }
五種方法都可以獲取vuex中的數據,其中兩個computed注掉一個可以測試另一個,這里全部列了出來,方法2使用了...擴展運算符的方式。
如果還有其他方法可以評論提出,相互探討
