Vuex的基本使用
Vuex是做什么的?
■官方解释: Vuex是一个专为Vue.js应用程序开发的状态管理模式。
它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以-种可预测的方式发生变化。
0Vuex 也集成到Vue的官方调试I具devtools extension ,提供了诸如零配置的time -travel调试、状态快照导入导出等高级调试功能。
■状态管理到底是什么 ?
状态管理模式、集中式存储管理这些名词听起来就非常高大上,让人捉摸不透。
其实,你可以简单的将其看成把需要多个组件共享的变量全部存储在一 个对象里面。
然后,将这个对象放在顶层的Vue实例中,让其他组件可以使用。
那么,多个组件是不是就可以共享这个对象中的所有变量属性了呢?
■等等, 如果是这样的话,为什么官方还要专门]出一个插件Vuex呢?难道我们不能自己封装一个对象来管理吗 ?
当然可以,只是我们要先想想VueJS带给我们最大的便利是什么呢?没错,就是响应式。
如果你自己封装实现一个对象能不能保证它里面所有的属性做到响应式呢 ?当然也可以,只是自己封装可能稍微麻烦-些。不用怀疑, Vuex就是为了提供这样一 个在多个组件间共享状态的插件,它就可以了。
index.js
import { createStore } from 'vuex'
const MouduleA = {
state: {
name:'zhangsan'
},
mutations: {
changename(state,payload) {
state.name = payload
},
name(state){
state.name='wangwu'
}
},
actions: {
/* moudule里面的actions的第一个参数不是store,而是这个moudule本身 */
name(context) {
setTimeout(() => {
context.commit('name')
},1000)
}
},
}
export default createStore({
state: {
message: 1000,
data: {
name: 'wyh',
age:'19'
}
},
mutations: {
/* 第一个是默认参数state */
add(state) {
state.message++
},
dec(state) {
state.message--
},
change(state) {
state.message=200
},
addcount(state,count) {
state.message += count
},
},
getters: {
pow(state) {
return state.message*state.message
},
},
actions: {
/* 异步操作在这里写,第一个参数默认是store对象,改state必须经过mutations环节 */
update(context,payload) {
return new Promise((reslove, reject) => {
setTimeout(() => {
context.commit('change')
console.log(payload);
reslove(111)
},1000)
})
}
},
modules: {
/* 多个store可以抽离很多模块 */
/* 这个a会被vuex放到state里面 */
a:MouduleA
}
})
组件内部
<template>
<div>
<h2>-------state的内容------- </h2>
<h1>{{$store.state.message}}</h1>
<h1>{{$store.state.data.name}}</h1>
<h1>{{$store.state.data.age}}</h1>
<h2>-------mutations的内容------- </h2>
<button @click="add">+</button>
<button @click="dec">-</button>
<button @click="add5(5)">+5</button>
<h2>-------action的内容------- </h2>
<button @click="update">修改messsge</button>
<!-- <h1>{{$store.getters.pow()}}</h1> -->
<h2>-------modules的内容-------</h2>
<p>{{$store.state.a.name}}</p>
<button @click="changename('lisi')">修改modules的name</button>
<button @click="name">异步修改name</button>
</div>
</template>
<script>
export default {
name: 'VuexHelloveux',
methods: {
/* 使用dispatch提交到mutations */
add(){
return this.$store.commit('add')
},
dec(){
return this.$store.commit('dec')
},
add5(num){
return this.$store.commit('addcount',num)
},
/* 添加state里的数据要想做到响应式要用set方法 */
addkeys(){
return this.$store.commit('addkeys')
},
update(){
/* 使用dispatch提交到action,还可以接收一个promise */
return this.$store.dispatch('update','参数').then(res=>{
console.log(res);
})
},
changename(payload){
return this.$store.commit('changename',payload)
},
name(){
return this.$store.dispatch('name')
}
},
};
</script>
<style scoped>
</style>
mapGetters 辅助函数
mapGetters 辅助函数仅仅是将 store 中的 getter 映射到局部计算属性:
import { mapGetters } from 'vuex'
export default {
// ...
computed: {
// 使用对象展开运算符将 getter 混入 computed 对象中
...mapGetters([
'doneTodosCount',
'anotherGetter',
// ...
])
}
}