Vue3复习和总结(vuex)
代码全部放在->github仓库:https://github.com/zyugat/vue-review-all
更多可看:zyugat.cn
前言:分为base、Component、router、Vuex、组合式API。5个部分。
base和Component中的例子不使用脚手架运行,需自行浏览器运行。位置->noCli
如果想更新Store状态,必须要先commit然后让vuex里面的mutations去改
yarn add vuex@next
目录:
- State
- 创建实例:
const store = createStore({})
- 获取数据:
this.$store.state.count
- Getters
- 获取:
$store.getters.powerCounter
- Mutations
- 调用:
this.$store.commit('方法名', 参数)
- Action
checkout ({ commit, state }, products) {}
- 调用:
this.$store.dispatch('方法名', 参数).then(res=>{})
- 模块
- 定义常量
- 命名空间
- 开启命名空间:
namespaced: true
- 组件中获取命名空间的State、Getters、Mutations、Action值
- 组件中使用
mapState
、mapGetters
、mapActions
和mapMutations
- 创建命名空间辅助函数:
createNamespacedHelpers
- 在命名空间的模块中访问全局内容
- 在命名空间的模块中注册全局 action
- 动态注册模块
State
创建一个store实例
import { createStore } from 'vuex'
// 创建一个新的 store 实例
const store = createStore({
state () {
return {
count: 0
}
},
mutations: {
increment (state) {
state.count++
}
}
})
获取数据:this.$store.state.count
获取多个状态:mapState
第一种:计算属性名称与 state 子节点名称不相同
// 在单独构建的版本中辅助函数为 Vuex.mapState
import { mapState } from 'vuex'
export default {
// ...
computed: mapState({
// 箭头函数可使代码更简练
count: state => state.count,
// 传字符串参数 'count' 等同于 `state => state.count`
countAlias: 'count',
// 为了能够使用 `this` 获取局部状态,必须使用常规函数
countPlusLocalState (state) {
return state.count + 10
}
})
}
第二种:计算属性名称和 state
节点名称相同
computed: mapState([
// 映射 this.count 为 store.state.count
'count'
])
第三种:与局部计算属性混用
mapState
函数返回的是一个对象。通过 对象展开运算符 将多个对象合并为一个。
computed: {
localComputed () { /* ... */ },
...mapState([
// 映射 this.count 为 store.state.count
'count'
])
}
Getters
计算属性,必须含有return
获取:$store.getters.powerCounter
用法:简单的计算属性、遍历对象、访问计算属性的方法、返回函数实现传参
const store = createStore({
state: {
count: 1,
todos: [
{ id: 1, text: 'todosText1', done: true },
{ id: 2, text: 'todosText2', done: false },
{ id: 3, text: 'todosText3', done: true },
],
},
getters: {
// 1、简单的计算属性
powerCount: state => {
return state.count * 2
},
// 2、遍历对象
doneTodos: state => {
return state.todos.filter(todo => todo.done)
},
// 3、访问计算属性的方法
doneTodosLength: (state, getters) => {
return getters.doneTodos.length
},
// 4、返回函数实现传参
getTodoById: state => id => {
return state.todos.find(todo => todo.id === id)
},
})
mapGetters
:将 store 中的 getter 映射到局部计算属性
import { mapGetters } from 'vuex'
export default {
// ...
computed: {
...mapGetters(['powerCounter', 'doneTodos', 'doneTodosLength']),
...mapGetters({
// 把 `this.doneCount` 映射为 `this.$store.getters.doneTodosCount`
getId: 'getTodoById',
}),
}
}
Mutations
对State数据进行操作
定义一个方法,在主页commit调用该方法。
this.$store.commit('方法名', 参数)
// vuex,定义方法
state: {
students: [
{ id: 1, text: 'wahaha', age: 18 },
{ id: 2, text: 'zhangsan', age: 25 },
],
}
mutations: {
addStudent: (state, stu) => {
state.students.push(stu)
},
},
// vue.vue,提交操作
addStudent() {
const stu = {id:114, name:'alan', age: 30}
// 普通参数传递
this.$store.commit('addStudent', stu)
// 使用对象传递
this.$store.commit({
type: 'addStudent',
stu
})
}
mapMutations
import { mapMutations } from 'vuex'
export default {
// ...
methods: {
...mapMutations([
'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`
// `mapMutations` 也支持载荷:
'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.commit('incrementBy', amount)`
]),
...mapMutations({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.commit('increment')`
})
}
}
Action
1、包含任意异步操作,提交的是 mutation,而不是直接变更状态,一般Action
是带参数的context
与payload
。
2、context具有store实例相同的方法和属性,可以通过context.commit
提交一个mulation,或者context.state
和context.getters
获取state和geteers。
3、使用:this.$store.dispatch('方法名', 参数).then(res=>{})
Action用于判断某个状态是什么,从而执行对应 mutations 方法
mutations: {
updateInfo(state) {
state.info.name = 'TETETE '
}
},
actions: {
// payload 是那边传来的参数
aUpdateInfo(context, payload) {
return new Promise((resolve, reject) => {
setTimeout(() => {
context.commit('updateActionInfo')
console.log(payload)
resolve('OK')
}, 1000)
})
},
// 通过参数解构简化代码
checkout ({ commit, state }, products) {}
},
Action同样也有:mapActions
import { mapActions } from 'vuex'
export default {
// ...
methods: {
...mapActions([
'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`
// `mapActions` 也支持载荷:
'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
]),
...mapActions({
add: 'increment' // 将 `this.add()` 映射为 `this.$store.dispatch('increment')`
})
}
}
组合式
store.dispatch
可以处理被触发的 action 的处理函数返回的 Promise,并且 store.dispatch
仍旧返回 Promise:
actions: {
async actionA ({ commit }) {
commit('gotData', await getData())
},
async actionB ({ dispatch, commit }) {
await dispatch('actionA') // 等待 actionA 完成
commit('gotOtherData', await getOtherData())
}
}
模块
目录:
store
modules
moduleA.js
actions.js 异步操作
getters.js 计算属性
index.js
mutations.js 方法
mutations-types.js 常量模块
通过利用export default {}
将内容导出,
获取 module 里面的 state:state.b.str
模块内部的 action 和 mutation 和 Getter 仍然是注册在全局命名空间的。
import moduleA from "./modules/moduleA";
import actions from "./actions";
import mutations from "./mutations";
import getters from "./getters";
const state = () => {
return {
count: 0,
}
}
export default createStore({
state,
mutations,
actions,
getters,
modules: {
a: moduleA,
b: {
state:{str:'mystr'},
mutations:{},
actions:{},
getters:{}
}
}
})
定义常量
mutations-types.js
// 1. 导出常量
export const INCREMENT = 'increment'
// 2. 导入常量
import {
INCREMENT
} from "@/store/mutations-types";
// 3. 使用常量
[INCREMENT](state) {
state.counter++
},
命名空间
1、默认情况下,模块内部的 action 和 mutation 和 Getter 仍然是注册在全局命名空间的。如果你不希望这样,可以开启命名空间namespaced: true,
。
export default createStore({
modules: {
a: moduleA,
b: {
state: { str: 'mystr' },
mutations: {
changeStr(state) {
state.str = 'changeStr'
},
},
actions: {},
getters: {},
},
// 命名空间
// 模块 account
account: {
namespaced: true,
state: () => {},
getters: {
isAdmin() {}, // -> getters['account/isAdmin']
},
actions: {
login() {}, // -> dispatch('account/login')
},
mutations: {
login() {
alert("commit('account/login')")
}, // -> commit('account/login')
},
modules: {
page: {
mutations: {
showPage() {
alert("commit('account/showPage')")
}, // -> commit['account/showPage']
},
},
// 进一步嵌套命名空间
posts: {
namespaced: true,
mutations: {
popular() {
alert("commit('account/posts/popular')")
}, // -> commit['account/posts/popular']
},
},
},
},
},
})
2、组件中获取命名空间的State、Getters、Mutations、Action:this.$store.state.moduleA.countA
computed: {
commonState(){
return this.$store.state.moduleA.countA
},
commonGetter(){
return this.$store.getters('moduleA/moduleAGetter')
},
// 2 此处的moduleA,不是以前缀的形式出现!!!
...mapGetters('moduleA',['moduleAGetter']),
// 3 别名状态下
...mapGetters({
paramGetter:'moduleA/moduleAGetter'
}),
},
methods: {
}
3、当使用 mapState
、mapGetters
、mapActions
和 mapMutations
这些函数来绑定带命名空间的模块时。
第二种方法:将模块的空间名称字符串作为第一个参数传递给上述函数,这样所有绑定都会自动将该模块作为上下文。
computed: {
// 第一种方法
...mapState({
a: state => state.some.nested.module.a,
b: state => state.some.nested.module.b
}),
// 第二种方法
...mapState('some/nested/module', {
a: state => state.a,
b: state => state.b
})
// 2 此处的moduleA,不是以前缀的形式出现!!!
...mapGetters('moduleA',['moduleAGetter']),
// 3 别名状态下
...mapGetters({
paramGetter:'moduleA/moduleAGetter'
}),
},
methods: {
commonAction(){
this.$store.dispatch('moduleA/moduleAAction')
},
...mapActions([
'some/nested/module/foo', // -> this['some/nested/module/foo']()
'some/nested/module/bar' // -> this['some/nested/module/bar']()
]),
...mapActions('some/nested/module', [
'foo', // -> this.foo()
'bar' // -> this.bar()
])
}
4、创建命名空间辅助函数:createNamespacedHelpers
const { mapState, mapActions } = createNamespacedHelpers('some/nested/module')
computed: {
// 在 `some/nested/module` 中查找
...mapState({
a: state => state.a,
b: state => state.b
})
},
在命名空间的模块中访问全局内容
rootState
和 rootGetters
会作为第三和第四参数传入 getter,也会通过 context
对象的属性传入 action。
getters: {
// 在这个模块的 getter 中,`getters` 被局部化了
// 你可以使用 getter 的第四个参数来调用 `rootGetters`
someGetter (state, getters, rootState, rootGetters) {
getters.someOtherGetter // -> 'foo/someOtherGetter'
rootGetters.someOtherGetter // -> 'someOtherGetter'
},
someOtherGetter: state => { ... }
},
在命名空间的模块中注册全局 action
root: true
,放在函数下。
actions: {
someAction: {
root: true,
handler (namespacedContext, payload) { ... } // -> 'someAction'
}
}
动态注册模块
store.registerModule
方法注册模块
store.unregisterModule(moduleName)
来动态卸载模块
import { createStore } from 'vuex'
const store = createStore({ /* 选项 */ })
// 注册模块 `myModule`
store.registerModule('myModule', {
// ...
})
// 注册嵌套模块 `nested/myModule`
store.registerModule(['nested', 'myModule'], {
// ...
})