什么是状态管理
在开发中,我们会的应用程序需要处理各种各样的数据,这些数据需要保存在我们应用程序中的某一个位置,对于这些数据的管理我们就称之为是状态管理。 在vue实例中我们是怎么管理状态呢?
- 而在组件中我们定义data或者在setup中返回使用的数据,这些数据我们称之为state
- 在模块template中我们可以使用这些数据,模块最终会被渲染成DOM,我们称之为View
- 在模块中我们会产生一些行为事件,处理这些行为事件时,有可能会修改state,这些行为事件我们称之为actions
对于一些简单的状态,确实可以通过props的传递或者Provide的方式来共享状态;但是对于复杂的状态管理来说,显然单纯通过传递和共享的方式是不足以解决问题的,比如兄弟组件如何共享数据呢?
因此,我们是否可以考虑将组件的内部状态抽离出来,以一个全局单例的方式来管理:
在这种模式下,我们的组件树构成了一个巨大的 “视图View”;不管在树的哪个位置,任何组件都能获取状态或者触发行为;通过定义和隔离状态管理中的各个概念,并通过强制性的规则来维护视图和状态间的独立性,我们的代码边会变得更加结构化和易于维护、跟踪;
vuex的使用
安装
npm install vuex
基本使用
每一个Vuex应用的核心就是store(仓库):store本质上是一个容器,它包含着你的应用中大部分的状态state Vuex和单纯的全局对象有什么区别呢?
- Vuex的状态存储是响应式的
- 改变store中的状态的唯一途径就显示提交 (commit) mutation
创建Store对象
import { craeteStore } from "vuex"
const store = createStore({
state: () => ({
counter: 0
}),
mutations: {
increment(state) {
state.counter++
}
}
})
export default store
在app中通过插件安装
import store from "./store"
createApp(App).use(store).mount("#app")
组件中使用
<template>
<div class="app">
<h2>Home当前计数: {{ $store.state.counter }}</h2>
<h2>Computed当前计数: {{ storeCounter }}</h2>
<h2>Setup当前计数: {{ counter }}</h2>
<button @click="increment">+1</button>
</div>
</template>
<script>
export default {
computed: {
storeCounter() {
return this.$store.state.counter
}
}
}
</script>
<script setup>
import { toRefs } from 'vue'
import { useStore } from 'vuex'
const store = useStore()
const { counter } = toRefs(store.state)
function increment() {
// store.state.counter++
store.commit("increment")
}
</script>
<style scoped>
</style>
mapState映射
之前通过store获取状态的方式太繁琐了,我们可以使用计算属性:
computed: {
counter() {
return this.$store.state.counter
}
}
如果我们有很多个状态都需要获取话,可以使用mapState的辅助函数:
- mapState的方式一:对象类型;
- mapState的方式二:数组类型;
- 也可以使用展开运算符和来原有的computed混合在一起;
<template>
<div class="app">
<button @click="incrementLevel">修改level</button>
<!-- 1.在模板中直接使用多个状态 -->
<h2>name: {{ $store.state.name }}</h2>
<h2>level: {{ $store.state.level }}</h2>
<h2>avatar: {{ $store.state.avatarURL }}</h2>
<!-- 2.计算属性(映射状态: 数组语法) -->
<!-- <h2>name: {{ name() }}</h2>
<h2>level: {{ level() }}</h2> -->
<!-- 3.计算属性(映射状态: 对象语法) -->
<!-- <h2>name: {{ sName }}</h2>
<h2>level: {{ sLevel }}</h2> -->
<!-- 4.setup计算属性(映射状态: 对象语法) -->
<!-- <h2>name: {{ cName }}</h2>
<h2>level: {{ cLevel }}</h2> -->
<!-- 5.setup计算属性(映射状态: 对象语法) -->
<h2>name: {{ name }}</h2>
<h2>level: {{ level }}</h2>
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
computed: {
fullname() {
return "xxx"
},
// name() {
// return this.$store.state.name
// },
...mapState(["name", "level", "avatarURL"]),
...mapState({
sName: state => state.name,
sLevel: state => state.level
})
}
}
</script>
<script setup>
import { computed, toRefs } from 'vue'
import { mapState, useStore } from 'vuex'
import useState from "../hooks/useState"
// 1.一步步完成
// const { name, level } = mapState(["name", "level"])
// const store = useStore()
// const cName = computed(name.bind({ $store: store }))
// const cLevel = computed(level.bind({ $store: store }))
// 2.使用useState
// const { name, level } = useState(["name", "level"])
// 3.直接对store.state进行解构(推荐)
const store = useStore()
const { name, level } = toRefs(store.state)
function incrementLevel() {
store.state.level++
}
</script>
<style scoped>
</style>
useState的封装
import { computed } from 'vue'
import { useStore, mapState } from 'vuex'
export default function useState(mapper) {
const store = useStore()
const stateFnsObj = mapState(mapper)
const newState = {}
Object.keys(stateFnsObj).forEach(key => {
newState[key] = computed(stateFnsObj[key].bind({ $store: store }))
})
return newState
}
getters基本使用
- 基本使用$store.getters.XXX
- getters函数有第二个参数
- getters里面定义的函数可以返回一个函数
import { createStore } from 'vuex'
import { CHANGE_INFO } from './mutation_types'
import homeModule from './modules/home'
import counterModule from './modules/counter'
const store = createStore({
state: () => ({
// 模拟数据
// counter: 100,
rootCounter: 100,
name: "coderwhy",
level: 100,
avatarURL: "http://xxxxxx",
friends: [
{ id: 111, name: "why", age: 20 },
{ id: 112, name: "kobe", age: 30 },
{ id: 113, name: "james", age: 25 }
],
// 服务器数据
// banners: [],
// recommends: []
}),
getters: {
// 1.基本使用
doubleCounter(state) {
return state.counter * 2
},
totalAge(state) {
return state.friends.reduce((preValue, item) => {
return preValue + item.age
}, 0)
},
// 2.在该getters属性中, 获取其他的getters
message(state, getters) {
return `name:${state.name} level:${state.level} friendTotalAge:${getters.totalAge}`
},
// 3.getters是可以返回一个函数的, 调用这个函数可以传入参数(了解)
getFriendById(state) {
return function(id) {
const friend = state.friends.find(item => item.id === id)
return friend
}
}
},
mutations: {
increment(state) {
state.counter++
},
})
export default store
<template>
<div class="app">
<!-- <button @click="incrementLevel">修改level</button> -->
<h2>doubleCounter: {{ $store.getters.doubleCounter }}</h2>
<h2>friendsTotalAge: {{ $store.getters.totalAge }}</h2>
<h2>message: {{ $store.getters.message }}</h2>
<!-- 根据id获取某一个朋友的信息 -->
<h2>id-111的朋友信息: {{ $store.getters.getFriendById(111) }}</h2>
<h2>id-112的朋友信息: {{ $store.getters.getFriendById(112) }}</h2>
</div>
</template>
<script>
export default {
computed: {
}
}
</script>
<script setup>
</script>
<style scoped>
</style>
mapGetters映射
<template>
<div class="app">
<button @click="changeAge">修改name</button>
<h2>doubleCounter: {{ doubleCounter }}</h2>
<h2>friendsTotalAge: {{ totalAge }}</h2>
<h2>message: {{ message }}</h2>
<!-- 根据id获取某一个朋友的信息 -->
<h2>id-111的朋友信息: {{ getFriendById(111) }}</h2>
<h2>id-112的朋友信息: {{ getFriendById(112) }}</h2>
</div>
</template>
<script>
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters(["doubleCounter", "totalAge"]),
...mapGetters(["getFriendById"])
}
}
</script>
<script setup>
import { computed, toRefs } from 'vue';
import { mapGetters, useStore } from 'vuex'
const store = useStore()
// 1.使用mapGetters
// const { message: messageFn } = mapGetters(["message"])
// const message = computed(messageFn.bind({ $store: store }))
// 2.直接解构, 并且包裹成ref
// const { message } = toRefs(store.getters)
// 3.针对某一个getters属性使用computed
const message = computed(() => store.getters.message)
function changeAge() {
store.state.name = "kobe"
}
</script>
<style scoped>
</style>
Mutations的使用
import { createStore } from 'vuex'
import { CHANGE_INFO } from './mutation_types'
import homeModule from './modules/home'
import counterModule from './modules/counter'
const store = createStore({
state: () => ({
// 模拟数据
// counter: 100,
rootCounter: 100,
name: "coderwhy",
level: 100,
avatarURL: "http://xxxxxx",
friends: [
{ id: 111, name: "why", age: 20 },
{ id: 112, name: "kobe", age: 30 },
{ id: 113, name: "james", age: 25 }
],
// 服务器数据
// banners: [],
// recommends: []
}),
getters: {
// 1.基本使用
doubleCounter(state) {
return state.counter * 2
},
totalAge(state) {
return state.friends.reduce((preValue, item) => {
return preValue + item.age
}, 0)
},
// 2.在该getters属性中, 获取其他的getters
message(state, getters) {
return `name:${state.name} level:${state.level} friendTotalAge:${getters.totalAge}`
},
// 3.getters是可以返回一个函数的, 调用这个函数可以传入参数(了解)
getFriendById(state) {
return function(id) {
const friend = state.friends.find(item => item.id === id)
return friend
}
}
},
mutations: {
increment(state) {
state.counter++
},
changeName(state, payload) {
state.name = payload
},
incrementLevel(state) {
state.level++
},
[CHANGE_INFO](state, newInfo) {
state.level = newInfo.level
state.name = newInfo.name
}
},
})
export default store
<template>
<div class="app">
<button @click="changeName">修改name</button>
<button @click="incrementLevel">递增level</button>
<button @click="changeInfo">修改info</button>
<h2>Store Name: {{ $store.state.name }}</h2>
<h2>Store Level: {{ $store.state.level }}</h2>
</div>
</template>
<script>
import { CHANGE_INFO } from "@/store/mutation_types"
export default {
computed: {
},
methods: {
changeName() {
// this.$store.state.name = "李银河"
this.$store.commit("changeName", "王小波")
},
incrementLevel() {
this.$store.commit("incrementLevel")
},
changeInfo() {
this.$store.commit(CHANGE_INFO, {
name: "王二",
level: 200
})
}
}
}
</script>
<script setup>
</script>
<style scoped>
</style>
mapMutations
<template>
<div class="app">
<button @click="changeName('王小波')">修改name</button>
<button @click="incrementLevel">递增level</button>
<button @click="changeInfo({ name: '王二', level: 200 })">修改info</button>
<h2>Store Name: {{ $store.state.name }}</h2>
<h2>Store Level: {{ $store.state.level }}</h2>
</div>
</template>
<script>
import { mapMutations } from 'vuex'
import { CHANGE_INFO } from "@/store/mutation_types"
export default {
computed: {
},
methods: {
btnClick() {
console.log("btnClick")
},
// ...mapMutations(["changeName", "incrementLevel", CHANGE_INFO])
}
}
</script>
<script setup>
import { mapMutations, useStore } from 'vuex'
import { CHANGE_INFO } from "@/store/mutation_types"
const store = useStore()
// 1.手动的映射和绑定
const mutations = mapMutations(["changeName", "incrementLevel", CHANGE_INFO])
const newMutations = {}
Object.keys(mutations).forEach(key => {
newMutations[key] = mutations[key].bind({ $store: store })
})
const { changeName, incrementLevel, changeInfo } = newMutations
</script>
<style scoped>
</style>
一条重要的原则就是要记住 mutation 必须是同步函数 这是因为devtool工具会记录mutation的日记;每一条mutation被记录,devtools都需要捕捉到前一状态和后一状态的快照;但是在mutation中执行异步操作,就无法追踪到数据的变化; 所以Vuex的重要原则中要求 mutation必须是同步函数,但是如果我们希望在Vuex中发送网络请求的话需要如何操作呢
anctions基本使用
import { createStore } from 'vuex'
import { CHANGE_INFO } from './mutation_types'
import homeModule from './modules/home'
import counterModule from './modules/counter'
const store = createStore({
state: () => ({
// 模拟数据
// counter: 100,
rootCounter: 100,
name: "coderwhy",
level: 100,
avatarURL: "http://xxxxxx",
friends: [
{ id: 111, name: "why", age: 20 },
{ id: 112, name: "kobe", age: 30 },
{ id: 113, name: "james", age: 25 }
],
// 服务器数据
// banners: [],
// recommends: []
}),
getters: {
// 1.基本使用
doubleCounter(state) {
return state.counter * 2
},
totalAge(state) {
return state.friends.reduce((preValue, item) => {
return preValue + item.age
}, 0)
},
// 2.在该getters属性中, 获取其他的getters
message(state, getters) {
return `name:${state.name} level:${state.level} friendTotalAge:${getters.totalAge}`
},
// 3.getters是可以返回一个函数的, 调用这个函数可以传入参数(了解)
getFriendById(state) {
return function(id) {
const friend = state.friends.find(item => item.id === id)
return friend
}
}
},
mutations: {
increment(state) {
state.counter++
},
changeName(state, payload) {
state.name = payload
},
incrementLevel(state) {
state.level++
},
[CHANGE_INFO](state, newInfo) {
state.level = newInfo.level
state.name = newInfo.name
// 重要的原则: 不要在mutation方法中执行异步操作
// fetch("xxxx").then(res => {
// res.json().then(res => {
// state.name = res.name
// })
// })
},
// changeBanners(state, banners) {
// state.banners = banners
// },
// changeRecommends(state, recommends) {
// state.recommends = recommends
// }
},
actions: {
incrementAction(context) {
// console.log(context.commit) // 用于提交mutation
// console.log(context.getters) // getters
// console.log(context.state) // state
context.commit("increment")
},
changeNameAction(context, payload) {
context.commit("changeName", payload)
},
})
export default store
<template>
<div class="home">
<h2>当前计数: {{ $store.state.counter }}</h2>
<button @click="counterBtnClick">发起action修改counter</button>
<h2>name: {{ $store.state.name }}</h2>
<button @click="nameBtnClick">发起action修改name</button>
</div>
</template>
<script>
export default {
methods: {
counterBtnClick() {
this.$store.dispatch("incrementAction")
},
nameBtnClick() {
this.$store.dispatch("changeNameAction", "aaa")
}
}
}
</script>
<script setup>
</script>
<style scoped>
</style>
mapActions
<template>
<div class="home">
<h2>当前计数: {{ $store.state.counter }}</h2>
<button @click="incrementAction">发起action修改counter</button>
<button @click="increment">递增counter</button>
<h2>name: {{ $store.state.name }}</h2>
<button @click="changeNameAction('bbbb')">发起action修改name</button>
</div>
</template>
<script>
import { mapActions } from 'vuex'
export default {
methods: {
// counterBtnClick() {
// this.$store.dispatch("incrementAction")
// },
// nameBtnClick() {
// this.$store.dispatch("changeNameAction", "aaa")
// }
// ...mapActions(["incrementAction", "changeNameAction"])
}
}
</script>
<script setup>
import { useStore, mapActions } from 'vuex'
const store = useStore()
// 1.在setup中使用mapActions辅助函数
// const actions = mapActions(["incrementAction", "changeNameAction"])
// const newActions = {}
// Object.keys(actions).forEach(key => {
// newActions[key] = actions[key].bind({ $store: store })
// })
// const { incrementAction, changeNameAction } = newActions
// 2.使用默认的做法
function increment() {
store.dispatch("incrementAction")
}
</script>
<style scoped>
</style>
Actions发送网络请求
actions可以返回一个promise
import { createStore } from 'vuex'
import { CHANGE_INFO } from './mutation_types'
import homeModule from './modules/home'
import counterModule from './modules/counter'
const store = createStore({
state: () => ({
// 模拟数据
// counter: 100,
rootCounter: 100,
name: "coderwhy",
level: 100,
avatarURL: "http://xxxxxx",
friends: [
{ id: 111, name: "why", age: 20 },
{ id: 112, name: "kobe", age: 30 },
{ id: 113, name: "james", age: 25 }
],
// 服务器数据
// banners: [],
// recommends: []
}),
getters: {
// 1.基本使用
doubleCounter(state) {
return state.counter * 2
},
totalAge(state) {
return state.friends.reduce((preValue, item) => {
return preValue + item.age
}, 0)
},
// 2.在该getters属性中, 获取其他的getters
message(state, getters) {
return `name:${state.name} level:${state.level} friendTotalAge:${getters.totalAge}`
},
// 3.getters是可以返回一个函数的, 调用这个函数可以传入参数(了解)
getFriendById(state) {
return function(id) {
const friend = state.friends.find(item => item.id === id)
return friend
}
}
},
mutations: {
increment(state) {
state.counter++
},
changeName(state, payload) {
state.name = payload
},
incrementLevel(state) {
state.level++
},
[CHANGE_INFO](state, newInfo) {
state.level = newInfo.level
state.name = newInfo.name
// 重要的原则: 不要在mutation方法中执行异步操作
// fetch("xxxx").then(res => {
// res.json().then(res => {
// state.name = res.name
// })
// })
},
// changeBanners(state, banners) {
// state.banners = banners
// },
// changeRecommends(state, recommends) {
// state.recommends = recommends
// }
},
actions: {
incrementAction(context) {
// console.log(context.commit) // 用于提交mutation
// console.log(context.getters) // getters
// console.log(context.state) // state
context.commit("increment")
},
changeNameAction(context, payload) {
context.commit("changeName", payload)
},
fetchHomeMultidataAction(context) {
// 1.返回Promise, 给Promise设置then
// fetch("http://123.207.32.32:8000/home/multidata").then(res => {
// res.json().then(data => {
// console.log(data)
// })
// })
// 2.Promise链式调用
// fetch("http://123.207.32.32:8000/home/multidata").then(res => {
// return res.json()
// }).then(data => {
// console.log(data)
// })
return new Promise(async (resolve, reject) => {
// 3.await/async
const res = await fetch("http://123.207.32.32:8000/home/multidata")
const data = await res.json()
// 修改state数据
context.commit("changeBanners", data.data.banner.list)
context.commit("changeRecommends", data.data.recommend.list)
resolve("aaaaa")
})
}
},
})
export default store
<template>
<div class="home">
<h2>Home Page</h2>
<ul>
<template v-for="item in $store.state.banners" :key="item.acm">
<li>{{ item.title }}</li>
</template>
</ul>
</div>
</template>
<script>
</script>
<script setup>
import { useStore } from 'vuex'
// 告诉Vuex发起网络请求
const store = useStore()
store.dispatch("fetchHomeMultidataAction").then(res => {
console.log("home中的then被回调:", res)
})
</script>
<style scoped>
</style>
module的基本使用
想建立一个home对象:
export default {
state: () => ({
// 服务器数据
banners: [],
recommends: []
}),
mutations: {
changeBanners(state, banners) {
state.banners = banners
},
changeRecommends(state, recommends) {
state.recommends = recommends
}
},
actions: {
fetchHomeMultidataAction(context) {
return new Promise(async (resolve, reject) => {
// 3.await/async
const res = await fetch("http://123.207.32.32:8000/home/multidata")
const data = await res.json()
// 修改state数据
context.commit("changeBanners", data.data.banner.list)
context.commit("changeRecommends", data.data.recommend.list)
resolve("aaaaa")
})
}
}
}
然后再在store/iindex.js中进行注册:
import { createStore } from 'vuex'
import { CHANGE_INFO } from './mutation_types'
import homeModule from './modules/home'
import counterModule from './modules/counter'
const store = createStore({
state: () => ({
// 模拟数据
// counter: 100,
rootCounter: 100,
name: "coderwhy",
level: 100,
avatarURL: "http://xxxxxx",
friends: [
{ id: 111, name: "why", age: 20 },
{ id: 112, name: "kobe", age: 30 },
{ id: 113, name: "james", age: 25 }
],
// 服务器数据
// banners: [],
// recommends: []
}),
getters: {
// 1.基本使用
doubleCounter(state) {
return state.counter * 2
},
totalAge(state) {
return state.friends.reduce((preValue, item) => {
return preValue + item.age
}, 0)
},
// 2.在该getters属性中, 获取其他的getters
message(state, getters) {
return `name:${state.name} level:${state.level} friendTotalAge:${getters.totalAge}`
},
// 3.getters是可以返回一个函数的, 调用这个函数可以传入参数(了解)
getFriendById(state) {
return function(id) {
const friend = state.friends.find(item => item.id === id)
return friend
}
}
},
mutations: {
increment(state) {
state.counter++
},
changeName(state, payload) {
state.name = payload
},
incrementLevel(state) {
state.level++
},
[CHANGE_INFO](state, newInfo) {
state.level = newInfo.level
state.name = newInfo.name
// 重要的原则: 不要在mutation方法中执行异步操作
// fetch("xxxx").then(res => {
// res.json().then(res => {
// state.name = res.name
// })
// })
},
// changeBanners(state, banners) {
// state.banners = banners
// },
// changeRecommends(state, recommends) {
// state.recommends = recommends
// }
},
actions: {
incrementAction(context) {
// console.log(context.commit) // 用于提交mutation
// console.log(context.getters) // getters
// console.log(context.state) // state
context.commit("increment")
},
changeNameAction(context, payload) {
context.commit("changeName", payload)
},
// fetchHomeMultidataAction(context) {
// // 1.返回Promise, 给Promise设置then
// // fetch("http://123.207.32.32:8000/home/multidata").then(res => {
// // res.json().then(data => {
// // console.log(data)
// // })
// // })
// // 2.Promise链式调用
// // fetch("http://123.207.32.32:8000/home/multidata").then(res => {
// // return res.json()
// // }).then(data => {
// // console.log(data)
// // })
// return new Promise(async (resolve, reject) => {
// // 3.await/async
// const res = await fetch("http://123.207.32.32:8000/home/multidata")
// const data = await res.json()
// // 修改state数据
// context.commit("changeBanners", data.data.banner.list)
// context.commit("changeRecommends", data.data.recommend.list)
// resolve("aaaaa")
// })
// }
},
modules: {
home: homeModule,
}
})
export default store
使用:$store.state.home.XXX
<template>
<div class="home">
<h2>Home Page</h2>
<ul>
<!-- 获取数据: 需要从模块中获取 state.modulename.xxx -->
<template v-for="item in $store.state.home.banners" :key="item.acm">
<li>{{ item.title }}</li>
</template>
</ul>
</div>
</template>
<script>
</script>
<script setup>
import { useStore } from 'vuex'
// 告诉Vuex发起网络请求
const store = useStore()
store.dispatch("fetchHomeMultidataAction").then(res => {
console.log("home中的then被回调:", res)
})
</script>
<style scoped>
</style>
module的局部状态
对于模块内部的 mutation 和 getter,接收的第一个参数是模块的局部状态对象 默认情况下,模块内部的action和mutation仍然是注册在全局的命名空间中的,这样使得多个模块能够对同一个 action 或 mutation 作出响应,Getter 同样也默认注册在全局命名空间 如果我们希望模块具有更高的封装度和复用性,可以添加 namespaced: true 的方式使其成为带命名空间的模块,当模块被注册后,它的所有 getter、action 及 mutation 都会自动根据模块注册的路径调整命名 创建counter对象:
const counter = {
namespaced: true,
state: () => ({
count: 99
}),
mutations: {
incrementCount(state) {
console.log(state)
state.count++
}
},
getters: {
doubleCount(state, getters, rootState) {
return state.count + rootState.rootCounter
}
},
actions: {
incrementCountAction(context) {
context.commit("incrementCount")
}
}
}
export default counter
import { createStore } from 'vuex'
import { CHANGE_INFO } from './mutation_types'
import homeModule from './modules/home'
import counterModule from './modules/counter'
const store = createStore({
state: () => ({
// 模拟数据
// counter: 100,
rootCounter: 100,
name: "coderwhy",
level: 100,
avatarURL: "http://xxxxxx",
friends: [
{ id: 111, name: "why", age: 20 },
{ id: 112, name: "kobe", age: 30 },
{ id: 113, name: "james", age: 25 }
],
// 服务器数据
// banners: [],
// recommends: []
}),
getters: {
// 1.基本使用
doubleCounter(state) {
return state.counter * 2
},
totalAge(state) {
return state.friends.reduce((preValue, item) => {
return preValue + item.age
}, 0)
},
// 2.在该getters属性中, 获取其他的getters
message(state, getters) {
return `name:${state.name} level:${state.level} friendTotalAge:${getters.totalAge}`
},
// 3.getters是可以返回一个函数的, 调用这个函数可以传入参数(了解)
getFriendById(state) {
return function(id) {
const friend = state.friends.find(item => item.id === id)
return friend
}
}
},
mutations: {
increment(state) {
state.counter++
},
changeName(state, payload) {
state.name = payload
},
incrementLevel(state) {
state.level++
},
[CHANGE_INFO](state, newInfo) {
state.level = newInfo.level
state.name = newInfo.name
// 重要的原则: 不要在mutation方法中执行异步操作
// fetch("xxxx").then(res => {
// res.json().then(res => {
// state.name = res.name
// })
// })
},
// changeBanners(state, banners) {
// state.banners = banners
// },
// changeRecommends(state, recommends) {
// state.recommends = recommends
// }
},
actions: {
incrementAction(context) {
// console.log(context.commit) // 用于提交mutation
// console.log(context.getters) // getters
// console.log(context.state) // state
context.commit("increment")
},
changeNameAction(context, payload) {
context.commit("changeName", payload)
},
// fetchHomeMultidataAction(context) {
// // 1.返回Promise, 给Promise设置then
// // fetch("http://123.207.32.32:8000/home/multidata").then(res => {
// // res.json().then(data => {
// // console.log(data)
// // })
// // })
// // 2.Promise链式调用
// // fetch("http://123.207.32.32:8000/home/multidata").then(res => {
// // return res.json()
// // }).then(data => {
// // console.log(data)
// // })
// return new Promise(async (resolve, reject) => {
// // 3.await/async
// const res = await fetch("http://123.207.32.32:8000/home/multidata")
// const data = await res.json()
// // 修改state数据
// context.commit("changeBanners", data.data.banner.list)
// context.commit("changeRecommends", data.data.recommend.list)
// resolve("aaaaa")
// })
// }
},
modules: {
home: homeModule,
counter: counterModule
}
})
export default store
使用:
<template>
<div class="home">
<h2>Home Page</h2>
<!-- 1.使用state时, 是需要state.moduleName.xxx -->
<h2>Counter模块的counter: {{ $store.state.counter.count }}</h2>
<!-- 2.使用getters时, 是直接getters.xxx -->
<h2>Counter模块的doubleCounter: {{ $store.getters["counter/doubleCount"] }}</h2>
<button @click="incrementCount">count模块+1</button>
</div>
</template>
<script>
</script>
<script setup>
import { useStore } from 'vuex'
// 告诉Vuex发起网络请求
const store = useStore()
// 派发事件时, 默认也是不需要跟模块名称
// 提交mutation时, 默认也是不需要跟模块名称
function incrementCount() {
store.dispatch("counter/incrementCountAction")
}
</script>
<style scoped>
</style>
如果想要在action中修改root中的state,那么有如下的方式:
changeNameAction({commit, dispatch, state, rootState, getters, rootGetters}) {
commit("changeRootName", null, {root:true})
dispatch("changeRootNameAction", null, {root:true})
}