1. 在store文件夹中,新建test.js文件,用于存放test模块的参数及相关方法。注意,内容都包含在export default{}中,没有原先index.js中默认带的new Vuex.Store字样。
export default{ // 和index.js中不同,没有new Vuex.Store
state: {
count:0, // 相当于data
num:1,
},
getters: {
doubleCount(state){
return 2 * state.count
}
},
mutations: { // 注意,函数实参为state
add(state){
state.count ++
},
decrease(state){
state.count --
}
},
actions: {
delayAdd(context){ // 主要,函数实参为context
setTimeout(() => {
context.commit('add')
}, 1000);
}
},
}
2. 改变store->index.js文件,引入新建的test.js,同时在export default中的modules中,声明这个模块。
import Vue from 'vue'
import Vuex from 'vuex'
import test from './test' // 引入模块
Vue.use(Vuex)
export default new Vuex.Store({
modules:{ // 设置模块
test
}
})
3. main.js中引入store,把默认的位置store改为,store/index
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store/index' // 改变引入store
// import 'element-ui/lib/theme-chalk/index.css';
Vue.config.productionTip = false
//导航守卫,每次切换路由时触发
router.beforeEach((to, from, next)=>{
console.log(to.path)
next()
})
// Vue.use(ElementUI);
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
4. 在使用该模块的位置Parent.vue中,status的引入方法不能直接用字符串了,应该使用箭头函数 state => state.test.count
<template>
<div style="background-color: dodgerblue;">
<!-- 读取store参数 方法一: $store.state.count -->
<h3>Parent <span style="color: red;">{
{ count }}</span></h3>
<!-- 读取store参数 方法二: this.$store.state.count 赋值到本地 -->
<!-- <h5>count: {
{ count }}</h5> -->
<!-- 读取getters中的数 -->
<h3>getters : {
{ doubleCount }}</h3>
<button @click="add">add</button>
<button @click="decrease">decrease</button>
<m-child></m-child>
</div>
</template>
<script>
import MChild from './Child.vue'
import { mapMutations, mapState,mapGetters } from 'vuex'
export default {
// computed: {
// // vuex,store中维护的数据,计算给count变量
// count() {
// return this.$store.state.count
// }
// },
// computed:mapState({
// count:'count'
// }),
computed:{
...mapState({
// count:'count'
count: state =>state.test.count
}),
// ...mapState([
// count
// ]),
// doubleCount(){
// return this.$store.getters.doubleCount
// }
...mapGetters([
'doubleCount'
])
},
data() {
return {
msg: 'df'
}
},
methods:{
...mapMutations(['add','decrease']), // 注意这里要用引号把函数名引起来
},
components: {
MChild,
},
mounted() {
console.log(this.$store.state)
}
}
</script>
<style></style>