1.vuex的引入
npm install vuex --save
2.main.js
import store from “vuex的js文件的路径”;
import Vue from “vue”;
3.vuex.js文件
import Vue from “vue”; import Vuex from "vuex"; Vue.use(Vuex); const state={ count:88 } const mutations={ jian(state){ count-- } } export default new Vuex.Store({ state, mutations })
4.vue组件获取store数据源
<template> <div id="me"> <div>{{$store.state.count}}</div> </div> </template> <script> export default{ name:"me", } </script>
5.vue组件通过computed获取数据源
<template> <div id="me"> <div>{{count}}</div> </div> </template> <script> export default{ name:"me", computed:{ count(){ return this.$store.state.count+1 } } } </script>
6.vue组件通过mapState获取数据源
<template> <div id="me"> <div >{{$store.state.count}}</div> </div> </template> <script> import {mapState} from ‘vuex‘; //引入mapState工具。 export default{ name:"me", // es6写法获取数据 computed:mapState({ count:state=>state.count }) //es5写法 computed:mapState({ count:function (state) { return state.count+2 }, }), //数组写法。 computed:mapState([ "count" ]) }
7.vue组件自己定义常量保存数据源
<template> <div id="me"> <div >{{count}}</div> </div> </template> <script> import {mapState} from ‘vuex‘; //引入mapState工具。 export default{ name:"me", // es6写法获取数据 computed:mapState({ count:state=>state.count }) //es5写法 computed:mapState({ count:function (state) { return state.count+2 }, }), //数组写法。 computed:mapState([ "count" ]) }