main.js中进行引入
import Vue from 'vue'
import Vuex from 'Vuex'
import store from './store'
Vue.use(Vuex)
export default new Vuex.store({
// 数据存储 相当于data
state: {
name: '张三',
age: 10,
count: 0,
list: [1,2,3,4,5,6,7,8,9]
},
// 就是vuex中的计算属性
getters: {
// 原始写法
// filterList: function(state) {
// return state.list.filter(item => item > 5)
// }
filterList: state => state.list.filter(item => item > 5),
// modules 模块的
token: state => state.user.token
},
// 里面定义方法,操作state方法
mutations: {
// 更改count的值
addCount(state, num) {
state.count += state.count + num
},
reduce(state) {
state.count--
}
},
// 异步操作放这里 等同mutation
actions: {
// 第一个参数是执行上下文对象,context相当于组件中的this.$store
// 第二个参数代表要传的值 可以不写
asyncAdd(conText, param) {
setTimeout(() => {
conText.commit("addCount", param)
})
}
},
modules: {
// 放置模块属性
user: {
namespaced: true, // 全局命名空间
state: {
token: '123456'
},
mutations: {
upd(state, num) {
state.token = num
}
}
},
login: {
state: {
name: '登录模块'
}
}
}
})
Vuex使用
使用state里的值
<!-- 方法一 -->
<div>{{ $store.state.name }}</div>
<!-- 方法二 -->
<!-- this.$store.state.全局数据名称 -->
this.$store.state.name
<!-- 方法三 -->
<!-- 从vuex中按需导入mapstate函数 -->
import { mapState, mapGetters, mapMutation, mapActions } from 'vuex'
computed: {
...mapState(['name', 'age', 'count'])
}
// 然后再标签直接使用
<div>{{ name + age + count }}</div>
getters的使用
<!-- 方法一 -->
// this.$store.getters.计算属性名
<div>{{ this.$store.getters.filterList }}</div>
<!-- 方法二 -->
// 先引用mapGetters,在使用
computed: {
...mapGetters(['filterList'])
}
mutations组件中使用
<!-- 方法一 使用commit触发Mutation操作 -->
methods: {
btn() {
this.$store.commit("addCount", 10)
},
btn1() {
this.$store.commit("reduce")
}
}
<!-- 方法二 使用辅助函数进行操作 -->
// 先引用mapMutation,在使用
methods: {
...mapMutation(["addCount", reduce]),
btn() {
this.addCount(10)
},
btn1() {
this.reduce()
}
}
actions组件中使用
<!-- 方法一 使用dispatch触发actions操作 -->
methods: {
btn() {
this.$store.dispatch("asyncAdd", 10)
}
}
<!-- 方法二 使用辅助函数进行操作 -->
// 先引用mapActions,在使用
methods: {
...mapActions(["asyncAdd"]),
btn() {
this.asyncAdd(10)
}
}
modules组件中使用
<!-- 使用state里的值 -->
this.$store.state.user.token
<!-- mutations的值使用 -->
<!-- 方法一 -->
methods: {
up() {
// namespaced未开启
this.$store.commit('upd', "123")
// namespaced开启
this.$store.commit('user/upd', '123')
}
}
<!-- 方法二 -->
methods: {
...mapMutation(['user/upd']),
up() {
this['user/upd']('123')
}
}
<!-- 方法三 通过createNamespacedHelpers 辅助函数 -->
import { createNamespacedHelpers } from 'vuex'
const { mapMutations } = createNamespacedHelpers('user')
methods: {
...mapMutations([upd]),
up() {
this.upd('123')
}
}