Vuex笔记
// store.js
import Vue from 'vue';
import Vuex from 'vuex'; //引入 vuex
import store from './store' //注册store
Vue.use(Vuex); //使用 vuex
export default new Vuex.Store({
state: {
// 初始化状态
count: 0,
someLists:[]
},
mutations: {
// 处理状态
increment(state, payload) {
state.count += payload.step || 1;
}
},
actions: {
// 提交改变后的状态
increment(context, param) {
context.state.count += param.step;
context.commit('increment', context.state.count)//提交改变后的state.count值
},
incrementStep({state, commit, rootState}) {
if (rootState.count < 100) {
store.dispatch('increment', {//调用increment()方法
step: 10
})
}
}
},
getters: {
//处理列表项
someLists: state =>param=> {
return state.someLists.filter(() => param.done)
}
}
})
//main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store' //引入状态管理 store
Vue.config.productionTip = false
new Vue({
router,
store,//注册store(这可以把 store 的实例注入所有的子组件)
render: h => h(App)
}).$mount('#app')
//views/home.vue
<template>
<div class="home">
<!--在前端HTML页面中使用 count-->
<HelloWorld :msg="count"/>
<!--表单处理 双向绑定 count-->
<input :value="count" @input="incrementStep">
</div>
</template>
<script>
import HelloWorld from '@/components/HelloWorld.vue'
import {mapActions, mapState,mapGetters} from 'vuex' //注册 action 和 state
export default {
name: 'home',
computed: {
//在这里映射 store.state.count,使用方法和 computed 里的其他属性一样
...mapState([
'count'
]),
count () {
return store.state.count
}
},
created() {
this.incrementStep();
},
methods: {
//在这里引入 action 里的方法,使用方法和 methods 里的其他方法一样
...mapActions([
'incrementStep'
]),
// 使用对象展开运算符将 getter 混入 computed 对象中
...mapGetters([
'someLists'
// ...
])
},
components: {
HelloWorld
}
}
</script>
运行结果下: