标签:efault cad cti 注册 pre eth lte lis from
1. 入口文件index.js
import Vuex from ‘vuex‘
import Vue from ‘vue‘
import modulesA from ‘./modules/modulesA‘
// 注册vuex到vue中
Vue.use(Vuex)
const state = {
counter:1,
todoList:[
{id:1,name:"learn vuex",done:true},
{id:2,name:"learn vue.js",done:true},
{id:3,name:"learn vue.js",done:false},
]
}
// new Vuex.Store() 实例
var store = new Vuex.Store({
state,
//getters对外提供数据,可对state中的数据过滤处理
getters:{
doneTodos(state){
return state.todoList.filter(item=>item.done);
},
counter(state){
return "counter:" + state.counter + "个";
}
},
// 同步操作
mutations:{
add(state,num){
state.counter += num;
},
sub(state,num){
state.counter -= num;
}
},
// 异步操作
actions:{
asyncAdd(context,num){
setTimeout(()=>{
context.commit(‘add‘,num)
})
}
},
//模块化管理数据
modules:{
modulesA,
}
})
export default store
组件中使用
<template>
<div class="com">
<h5>home</h5>
<ul>
<li v-for="item in $store.getters.doneTodos">{{item.name}}</li>
</ul>
<p>
{{$store.getters.counter }}
</p>
<p> <button @click="add(2)">+2</button>
<span class="counter">{{$store.state.counter}}</span>
<button @click="sub(2)">-2</button></p>
<div>异步<button @click="asyncAdd(10)">+10</button></div>
<div>
<p>获取模块A数据isAdmin:{{$store.state.modulesA.isAdmin}}</p>
</div>
</div>
</template>
<script>
export default {
data() {
return {}
},
methods: {
add(num) {
this.$store.commit(‘add‘, num);
},
sub(num) {
this.$store.commit(‘sub‘, num);
},
asyncAdd(num){
this.$store.dispatch(‘asyncAdd‘, num);
}
}
}
</script>
挂载store
new Vue({
el: ‘#app‘,
router,
store,
components: { App },
template: ‘<App/>‘
})
2. 总结
2.1 state中的数据,不能(不建议)直接修改,如果想要修改,必须通过 mutations(同步)/actions(异步)
2.2 从 state 上获取数据,需要 this.$store.state.***,例如 :$store.state.counter
2.3 使用 getters ,则用 this.$store.getters.***,例如 :$store.getters.counter
2.4 调用mutations中的方法this.$store.commit(‘方法的名称‘, 参数) ,例如:this.$store.commit(‘sub‘, num);
2.5 调用actions中的方法this.$store.dispatch(‘方法的名称‘, 参数) ,例如:this.$store.dispatch(‘asyncAdd‘, num);
标签:efault cad cti 注册 pre eth lte lis from
原文地址:https://www.cnblogs.com/jlyuan/p/12099444.html