vuex
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。可以想象为一个“前端数据库”(数据仓库),
让其在各个页面上实现数据的共享包括状态,并且可操作
Vuex分成五个部分:
1.State:单一状态树
2.Getters:状态获取
3.Mutations:触发同步事件
4.Actions:提交mutation,可以包含异步操作
5.Module:将vuex进行分模块
vuex使用步骤
安装
cmd 切换到你项目的路径下 输入下载 npm install vuex -S
下载后会显示的下载的版本号
创建store模块,分别维护state/actions/mutations/getters
store
index.js
state.js
actions.js
mutations.js
getters.js
vuex的核心概念:store、state、getters、mutations、actions
vex相关代码块
</el-menu-item>
<el-menu-item index="/Page1">
<i class="el-icon-s-home"></i>
<span slot="title">Page1</span>
</el-menu-item>
<el-menu-item index="/Page2">
<i class="el-icon-s-home"></i>
<span slot="title">Page2</span>
</el-menu-item>
page1
<template>
<div style="margin: 15px;">
<h1>Page1,ts={{ts}}</h1>
<h2>{{name}}</h2>
</div>
</template>
<script>
export default{
data:function(){
return{
ts:new Date().getTime()
};
},
computed:{
name:function(){
//不推荐使用
return this.$store.state.resturantName;
}
}
}
</script>
<style>
</style>
page2
<template>
<div style="margin: 15px;">
<h1>Page2,ts={{ts}}</h1>
<h2>{{name}}</h2>
<div>
<button @click="doMutation">mutations之同步方式赋值</button>
<button @click="doActionAsync">actions之异步方式静态数据赋值</button>
<button @click="doActionAsyncAjax">actions之异步方式动态数据赋值</button>
</div>
</div>
</template>
<script>
export default{
data:function(){
return{
ts:new Date().getTime()
};
},
methods:{
doMutation:function(){
//错误方式
//this.$store.mutations.setName();
//正确方式
this.$store.commit('setName',{
name:'aaaa'
});
},
doActionAsync:function(){
this.$store.dispatch('setNameAsync',{
name:'bbbbbb'
});
},
doActionAsyncAjax:function(){
this.$store.dispatch('setNameAsyncAjax',{
name:'cccccc',
_this:this
});
}
},
computed:{
name:function(){
//不推荐使用
//return this.$store.state.resturantName;
//使用getters方式获取值
return this.$store.getters.getName;
}
}
}
</script>
<style>
</style>
结果图: