state
核心成员一:state 存放数据的位置
访问方式一:直接访问 this.$store.state.XXX
访问方式二: ...mapState(['count', 'title'])
mutations
核心成员二:mutations 操作 state 的唯一途径
mutations 函数只有两个参数,如果需要携带多个参数,可以传对象
所有的 mutation 函数第一个参数必须是 statoe
所有的 mutation 函数第二个参数必须是 payload (载荷)
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
// 开启严格模式
strict: true,
// 核心成员一:state 存放数据的位置
// 访问方式一:直接访问 this.$store.state.XXX
// 访问方式二: ...mapState(['count', 'title'])
state: {
count: 100,
title: '大风'
},
// 核心成员二:mutations 操作 state 的唯一途径
// mutations 函数只有两个参数,如果需要携带多个参数,可以传对象
mutations: {
// 所有的 mutation 函数第一个参数必须是 statoe
// 所有的 mutation 函数第二个参数必须是 payload (载荷)
aClic (state, n) {
state.count += n
}
}
})
mapMutations 辅助函数
辅助函数复用性更好,但是要配置
import { mapMutations } from 'vuex'
=============================================
methods: {
// 辅助函数复用性更好,但是要配置
...mapMutations(['aClic'])
}
// 辅助函数相当于
cli (i) {
this.$store.commit('aClic', i)
},
==========================================
//使用 aClic(参数)
<button @click="aClic(1)" class="btn btn-primary">
actions 专做异步任务
核心成员三:actions 专做异步任务
参数一:必须是 context 用来获取要使用的 函数
参数二:传递过来的参数
// 核心成员三:actions 专做异步任务
actions: {
// 参数一:必须是 context 用来获取要使用的 函数
// 参数二:传递过来的参数
asySet (context, n) {
// 定时器异步任务
setTimeout(() => {
context.commit('xInp', n)
}, 1000)
}
}
=====================================
// 在组件中使用
asyCli () {
// dispatch 是调用 actioons 的函数,用法和 commit 一样
this.$store.dispatch('asySet', 123)
}
getters 计算属性
核心成员四:getters 计算属性,供所有组件使用的计算属性
所有的 getters 第一个参数都是 state
注意:必须要有返回值
// 核心成员四:getters 计算属性,供所有组件使用的计算属性
getters: {
// 所有的 getters 第一个参数都是 state
// 注意:必须要有返回值
getList (state) {
return state.list.filter(item => item > 5)
}
}
========================================
<p>getList: {{ $store.getters.getList }}</p>
模块 module (进阶语法)
核心成员五:modules 分模块
1、新建子模块,导出四个核心成员对象
export default {
state: {
userInfo: {
name: 'ls',
age: 28
}
},
mutations: {
},
actions: {
},
getters: {
}
}
2、在 store/index.js 中引入并注册模块
import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'
// 注册模块
import setting from './modules/setting'
Vue.use(Vuex)
const store = new Vuex.Store({
// 开启严格模式
strict: true,
modules: {
// 导入模块
user,
setting
}
})
export default store
辅助函数
在 模块 module 中 使用辅助函数,相比于之前,需要传递一个参数为模块名,其他照旧 (多次使用时,建议使用 辅助函数)
namespaced: true 命名空间
命名空间:给子模块提供一个独立的空间,以自己模块名名命名的空间,建议所有的子模块都开启
// 开启命名空间,以防同名
namespaced: true