vue3
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45import { createStore } from 'vuex' // vue2.0 创建仓库 new Vuex.Store({ }) // vue3.0 创建仓库 createStore({ }) export default createStore({ state: { // 数据 username: 'zs', age: 56 }, getters: { // vuex的计算属性 newName (state) { return state.username + '!!!' }, }, mutations: { // 更改数据函数 updateName (state) { state.username = 'ls' }, updateAge (state, playLoad) { console.log("playLoad", playLoad) state.age += playLoad } }, actions: { // Action 类似于 mutation,不同在于: // Action 提交的是 mutation,而不是直接变更状态。 // Action 可以包含任意异步操作。 // 请求数据函数 updateName (ctx) { console.log('触发了') // 发请求 setTimeout(() => { ctx.commit('updateAge', 46) }, 1000) } }, modules: { // 分模块 } })
App.vue
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46<template> <!-- vue2.0需要根元素,vue3.0可以是代码片段 fragment --> <div> App <!-- 1、使用根模块state的数据 --> <h1>{{ $store.state.username }}</h1> <!-- 2、使用根模块getters的数据 --> <h1>{{ $store.getters.newName }}</h1> <h1>{{ $store.getters["newName"] }}</h1> <button @click="mutationsFn">按钮</button> <h1>{{ $store.state.age }}</h1> <button @click="actionsFn">改变年龄</button> </div> <p>p</p> </template> <script> import { useStore } from "vuex"; export default { name: "App", setup () { // userStore可以拿到vuex仓库实例 const store = useStore(); // 1、使用根模块state的数据 console.log(store); console.log(store.state.username); // 2、使用根模块getters的数据 console.log(store.getters.newName); // 3、提交根模块mutations方法 const mutationsFn = () => { store.commit("updateName"); }; // 4、调用根模块的actions函数 const actionsFn = () => { store.dispatch('updateName') } return { mutationsFn, actionsFn } }, }; </script> <style lang="less"> </style>
最后
以上就是怕黑萝莉最近收集整理的关于vue3根模块中vuex的使用,vuex的全部内容,更多相关vue3根模块中vuex内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复