vuex介绍
. Vuex
官方解释:Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。可以想象为一个“前端数据库”(数据仓库),
让其在各个页面上实现数据的共享包括状态,并且可操作
Vuex分成五个部分:
1.State:单一状态树
2.Getters:状态获取
3.Mutations:触发同步事件
4.Actions:提交mutation,可以包含异步操作
5.Module:将vuex进行分模块
安装vuex
npm install vuex -S
**创建store模块,分别维护state/actions/mutations/getters
在src下的store目录
index.js
state.js
actions.js
mutations.js
getters.js
建5个js文件
注意首字母大写
**
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引用
上面
import store from './store'
data里面
store
在里面定义一个值
通过
this.$store.state.resturantName;
拿到这个值
不建议这种方法
因为State里面只用来储存数据取要从别的地方取
在Getters.js里面写取的方法
export default {
setresturantName: (state) => {
return state.resturantName;
}
}
通过 return this.$store.getters.getResturantName;取到值
设置值在Mutations.js
export default {
setResturantName: (state, payload) => {
state.resturantName = payload.resturantName;
}
}
通过
this.$store.commit(‘setResturantName’, {
resturantName: ‘KFC’
})
设置值
刚刚是同步修改
异步修改
在Actions中写
//3000代表三秒钟可以执行完在执行的过程中可以做别的是提高了效率
export default {
setResturantNameByAsync: (context, payload) => {
setTimeout(() => {
context.commit('setResturantName', payload); //Action提交的是mutation
}, 3000)
}
}
this.$store.dispatch('setResturantNameByAsync', {
resturantName: '异步修改'
})
这里设置修改异步需要三秒
我先带你修改异步然后再点修改同步两个可以一起执行而不是等一个执行完再执行
所有代码
VuexPage1
<template>
<div>
<h3>页面1:欢迎来到{{msg}}</h3>
<button type="primary" @click="buy">修改(同步)</button>
<button type="primary" @click="buyAsync">修改(异步)</button>
</div>
</template>
<script>
export default {
name: 'VuexPage1',
data() {
return {}
},
computed: {
msg() {
return this.$store.getters.getResturantName;
}
},
methods: {
buy() {
this.$store.dispatch('setResturantNameByAsync', {
resturantName: '同步修改'
})
},
buyAsync(){
this.$store.dispatch('setResturantNameByAsync', {
resturantName: '异步修改'
})
}
}
}
</script>
<style>
</style>
VuexPage2
<template>
<div>
<h3>页面2:欢迎来到{{msg}}</h3>
</div>
</template>
<script>
export default {
name: 'VuexPage2',
data() {
return {
}
},
computed:{
msg(){
return this.$store.getters.getResturantName;
}
}
}
</script>
<style>
</style>