Vuex
官方解释:Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。可以想象为一个“前端数据库”(数据仓库),
让其在各个页面上实现数据的共享包括状态,并且可操作
Vuex分成五个部分:
1.State:单一状态树
2.Getters:状态获取
3.Mutations:触发同步事件
4.Actions:提交mutation,可以包含异步操作
5.Module:将vuex进行分模块
使用Vuex:
在项目文件所在目录打开窗口安装
npm install vuex -S
在package.json查看
创建store模块,分别维护state/actions/mutations/getters
在store/index.js文件中新建vuex的store实例,并注册上面引入的各大模块
index.js:
import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import getters from './getters'
import actions from './actions'
import mutations from './mutations'
Vue.use(Vuex)
const store = new Vuex.Store({
state,
getters,
actions,
mutations
})
export default store
在main.js中导入并使用store实例
之后按要求编码,即可使用vuex的相关功能
State.js(共同维护的一个状态,state里面可以是很多个全局状态):
export default {
//定义变量 可以写很多变量 集中管理 可在jsong对象里面再套一个obj对象 分类管理
resturantName:'开森餐馆'
}
Getters(获取数据并渲染):
export default{
getResturantName:(state)=>{
return state.resturantName;
}
}
Mutations.js(处理数据的唯一途径,state的改变或赋值只能在这里):
export default{
setResturantName: (state, payload) => {
state.resturantName = payload.resturantName;
}
}
Actions.js(数据的异步操作):
export default {
setResturantNameAsync: (content, payload) => {
console.log('xxx');
setTimeout(() => {
console.log('yyy');
content.commit('setResturantName', {
resturantName: payload.resturantName
})
}, 6000);
console.log('zzz');
},
doAjax: (context, payload) => {
let _this = payload._this
let url = _this.axios.urls.SYSTEM_USER_DOLOGIN;
_this.axios.post(url, {}).then((response)=> {
console.log(response);
}).catch(function(error) {
console.log(error);
});
}
}
两个界面:
VuePage1.vue:
<template>
<div>
年轻人都爱来:{{title}}<br />
<input v-model="newName" />
<button @click="buy">同步存值</button>
<button @click="badbuy">异步存值</button>
<button @click="doAjax">调用ajax</button>
</div>
</template>
<script>
export default {
data() {
return {
newName:''
};
},
computed: {//计算属性 :state状态存储是响应式的,从store实例中读取状态最简单的方法就是在计算属性中返回某个状态
title() {//不建议
return this.$store.state.resturantName;
}
},
methods: {
buy() {//同步
this.$store.commit('setResturantName',{
resturantName:this.newName
})
},
badbuy(){//异步
this.$store.dispatch('setResturantNameAsync',{
resturantName:this.newName
})
},
doAjax(){//为了在异步里使用ajax 将this传递过去
this.$store.dispatch('doAjax',{
_this:this
})
}
}
}
</script>
<style>
</style>
VuePage2.vue:
<template>
<div>
年轻人都爱:{{title}}
</div>
</template>
<script>
export default {
data() {
return {
};
},
computed: {
title() {
return this.$store.getters.getResturantName;
}
},
}
</script>
<style>
</style>
下图展示效果:
同步存值:
异步存值:
调用ajax: