vuex有哪几种属性和使用
Vuex是在大型项目中,组件之间传值不易,用vuex集中管理状态
场景有:单页应用中,组件之间的状态
一、属性介绍
分别是 State、 Getter、Mutation 、Action、 Module
state => 基本数据(数据源存放地)(this.$store.state直接用)
getters => 从基本数据派生出来的数据
mutations => 提交更改数据的方法,同步!
actions => 像一个装饰器,包裹mutations,使之可以异步。
(放异步数据请求,如果不是异步请求,组件可以直接调用commit触发mutations的方法)
modules => 模块化Vuex
但是组件不能直接修改state中的数据,如果要修改需通过this.$store.dispath触发actions中定义的方法
在actions中,通过ctx.commit()触发mutations中定义的方法
在mutations中可以修改state值
一、获取值
main.js
store.state..msg
index.vue
this.$store.state.msg
<p>
vuex的msg数据是:
<span>{{ this.$store.state.msg }}</span>
</p>
二、改值
store.js
state: {
num: 88,
},
actions: {
changeactnum(ctx, data) {
ctx.commit('changemutnum', data)
}
},
mutations: {
changemutnum(state, data) {
state.num = data
}
},
index.vue
//有异步操作,先调用actions中的cxt.commit()去调用mutations中的方法
changenum() {
let num = 100
this.$store.dispatch('changeactnum', num)
},
// 如果没有异步操作,也可以直接用commit调用 mutations中的方法
changenum() {
let num = 100
this.$store.commit('changemutnum', num)
}
三、辅助函数 mapMutations, mapActions
store.js
state: {
num: 88,
},
actions: {
changeactnum(ctx, data) {
ctx.commit('changemutnum', data)
}
},
mutations: {
changemutnum(state, data) {
state.num = data
}
},
index.vue
import {mapMutations, mapActions } from 'vuex'
// 辅助函数mapActions
...mapActions(['changeactnum']),
changenum() {
let num = 100
this.changeactnum(num)
}
// 辅助函数mapMutations
...mapMutations(['changemutnum']),
changenum() {
let num = 100
this.changemutnum(num)
},
四、辅助函数 mapState
store.js
state: {
city: '郑州'
}
index.vue
<p>{{ city }}</p>
import { mapState} from 'vuex'
computed: {
//辅助函数mapState mapGetters
...mapState(['city']),
},
五、辅助函数 mapGetters
store.js
state: {
students: [
{ id: '1', name: 'Amy', age: 20 },
{ id: '3', name: 'Alice', age: 34 },
{ id: '4', name: 'Green', age: 210 },
{ id: '5', name: 'Jack', age: 40 },
{ id: '6', name: 'Grace', age: 10 }
],
},
getters: {
selectedStudents(state) {
return state.students.filter(item => item.age > 30)
}
},
index.vue
<ul>
<li v-for="(item, index) in selectedStudents" :key="item.id">
{{ item.name }}--{{ item.age }}---{{ index }}
</li>
</ul>
import { mapGetters} from 'vuex'
computed: {
//辅助函数mapGetters
...mapGetters(['selectedStudents']),
},