vuex的module模块用法

第一步:在store文件夹下的index.js入口文件写入:

import Vue from 'vue';
import Vuex from 'vuex';
import feeds from './feeds/index'
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
feeds
}
})

第二步:在每个模块内的index文件这组装所有的零件,并且输出

export default {
namespaced: true,//必须加它不然报错
state:{
number:1
},
mutations: {
add(state,playload) {
state.number +=playload;
}
},
actions:{
addAction(context){
context.commit('add',10);
}
}
}
注意上面多出的一行,我们在组件里怎么区分不同模块呢?namespaced写成true,意思就是可以用这个module名作为区分了(也就是module所在的文件夹名)
最好使用store 将其放进main.js中,代码如下:
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store/index'

Vue.config.productionTip = false

new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
这样就可以使用moudules中的state,mutations,actions,代码如下:
import { mapState,mapActions,mapMutations } from 'vuex'
export default {
name: 'home',
computed: {
...mapState('feeds',{
number: state =>state.number
})

},
methods: { //模块名必须写清楚
...mapActions('feeds',[ //
'addAction'
]),
...mapMutations('feeds',[
'add',
]),
}
}
html代码如下:
<template>
<div class="home">
{{this.$store.state.feeds.number}}
<br/>
{{number}}
//调用mutations的方法
<button @click="add(1)">加</button>
<br/>
<br/> //调用调用actions的方法
    <button @click="addAction">action加</button>
</div>
</template>

另外我们也可以通过this.$store来获取modules中的state比变量和mutations和actions的方法
代码如下:
<template>
<div class="about">
<h1></h1>
{{this.$store.state.feeds.number}}
<br>
<!--调用mutations的方法-->
<button @click="add">mutations加</button>
<br>
<br> <!--调用actions的方法-->
<button @click="addaction">actions加</button>
</div>
</template>
<script>
import { mapState,mapActions,mapMutations } from 'vuex'
export default {
name: 'home',

methods: {
add() {
this.$store.commit('feeds/add',10)
},
addaction() {
this.$store.dispatch('feeds/addAction') ;
}

}
}
</script>
 
 
 

猜你喜欢

转载自www.cnblogs.com/zhx119/p/11010840.html