vuex是一个专为 Vue.js 应用程序开发的状态管理模式
vuex一般在大中型单页面应用中使用,如果您不打算开发大型单页应用,使用 Vuex 可能是繁琐冗余的。
安装vuex依赖
cnpm install vuex --save-dev
引用store,store实例也可以写在main.js中,但是考虑项目过大,把store写在main.js中会降低代码可读性,所以单独创建一个store文件来应用vuex(见下文index.js)
- main.js
import store from './store/index'
创建store,使用vuex状态管理模式
- index.js
import vue from 'vue'
import vuex from 'vuex'
Vue.use(vuex); //使用vuex
const state = {
count:1
};
//随着mutations越来越复杂,增加actions用来管理mutations
const actions = {
add:({commit,state})=>{
commit('add')
},
del:({commit,state})=>{
commit('del')
}
};
//用于修改状态
const mutations = {
add:(state)=>{
state.coumt++;
},
del:(state)=>{
if(state.count>2){
state.count--;
}
}
};
const store = new vuex.Store({ //创建仓库,仓库中添加state
state,
actions,
mutations
});
//导出store对象
export default store;
设置改变数据状态,渲染数据到视图
Find.js
<template>
<div>
<!-- state -->
{{$store.state.flag}}
<!--<button @click="$store.state.flag='click'">click</button>-->
<!--mutations 改变数据的状态-->
<!--使用$store.commit('abc')会触发mutations中的abc方法-->
<!--<button @click="$store.commit('abc')">mutations</button>-->
<!--执行多个mutations 需要actions来进行管理-->
<!--<button @click="$store.dispatch('abc')">dispatch</button>-->
<button @click="add">添加</button>
<button @click="del">删除</button>
{{count}}
</div>
</template>
<script>
import {mapState,mapGetters,mapActions} from 'vuex'
export default{
data(){
return {
}
}
methods:{
add(){
this.$store.dispatch('add')
},
del(){
this.$store.dispatch('del')
}
},
//computed:{ //方法一
// count2(){
// return this.$store. state.count
// }
//},
computed:mapState(['count']) //获取值方法2
}
</script>
参考文章: