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