Vue3中Vuex状态管理库学习笔记(二)
2019ab/CSDN发表于:2024-05-13 15:42:11浏览:100次
10.mapMutations的使用
- 在options-api中
<template>
<div>
<button @click="changeName">修改name</button>
<h2>Store Name:{{ $store.state.name }}</h2>
<button @click="changeLevel">修改level</button>
<h2>Store Level:{{ $store.state.level }}</h2>
<button @click="changeInfo({name:'张三',level:'1999'})">修改level和name</button>
</div>
</template>
<script>
import { mapMutations } from "vuex";
import {CHANGE_INFO } from "@/store/mutation_types"
export default {
computed:{
},
methods:{
btnClick(){
console.log("btnClick")
},
...mapMutations(["changeName","changeLevel",CHANGE_INFO])
}
}
</script>
<style scoped>
</style>
- composition-api中
<template>
<div>
<button @click="changeName">修改name</button>
<h2>Store Name:{{ $store.state.name }}</h2>
<button @click="changeLevel">修改level</button>
<h2>Store Level:{{ $store.state.level }}</h2>
<button @click="changeInfo({name:'张三',level:'1999'})">修改level和name</button>
</div>
</template>
<script setup>
import { mapMutations,useStore } from 'vuex';
import { CHANGE_INFO } from "@/store/mutation_types"
const store = useStore();
// 1.手动映射和绑定
const mutations = mapMutations(["changeName","changeLevel",CHANGE_INFO])
const newMutations = {}
Object.keys(mutations).forEach(key => {
newMutations[key] = mutations[key].bind({$store:store})
})
const { changeName,changeLevel,changeInfo } = newMutations
</script>
<style scoped>
</style>
mutation重要原则
1.一条重要的原则就是要记住mutation必须是同步函数
- 这是因为devtool工具会记录mutation的日记
- 每一条mutation被记录,devtools都需要捕捉到前一状态和后一状态的快照
- 但是在mutation中执行异步操作,就无法追踪到数据的变化
11. Actions的基本使用
<template>
<div>
<h2>当前计数:{{ $store.state.counter }}</h2>
<button @click="actionBtnClick">发起action</button>
<h2>当前计数:{{ $store.state.name }}</h2>
<button @click="actionchangeName">发起action修改name</button>
</div>
</template>
<script>
export default {
computed:{
},
methods:{
actionBtnClick(){
this.$store.dispatch("incrementAction")
},
actionchangeName(){
this.$store.dispatch("changeNameAction","bbb")
}
}
}
</script>
<script setup>
</script>
<style scoped>
</style>
mapActions的使用
componets-api和options-api的使用
<template>
<div>
<h2>当前计数:{{ $store.state.counter }}</h2>
<button @click="incrementAction">发起action</button>
<h2>当前计数:{{ $store.state.name }}</h2>
<button @click="changeNameAction('bbbccc')">发起action修改name</button>
<button @click="increment">increment按钮</button>
</div>
</template>
<!-- <script>
import { mapActions } from 'vuex';
export default {
computed:{
},
methods:{
...mapActions(["incrementAction","changeNameAction"])
}
}
</script> -->
<script setup>
import { useStore,mapActions } from 'vuex';
const store = useStore();
const actions = mapActions(["incrementAction","changeNameAction"]);
const newActions = {}
Object.keys(actions).forEach(key => {
newActions[key] = actions[key].bind({$store:store})
})
const {incrementAction,changeNameAction} = newActions;
// 2.使用默认的做法
// import { useStore } from 'vuex';
// const store = useStore();
// function increment(){
// store.dispatch("incrementAction")
// }
</script>
<style scoped>
</style>
actions发起网络请求
- store/index.js文件
import { createStore } from "vuex";
import { CHANGE_INFO } from "./mutation_types";
const store = createStore({
state:() => ({
counter:100,
name:'why',
level:10,
users:[
{id:111,name:'why',age:20},
{id:112,name:'kobe',age:30},
{id:113,name:'james',age:25},
],
friends:[
{id:111,name:'why',age:20},
{id:112,name:'kobe',age:30},
{id:113,name:'james',age:25},
],
// // 服务器数据
banners:[],
recommends:[]
}),
getters:{
doubleCounter(state){
return state.counter * 2
},
totalAge(state){
return state.users.reduce((preValue,item)=>{
return preValue + item.age
},0)
},
message(state){
return `name:${state.name} level:${state.level}`
},
// 获取某一个frends,是可以返回函数的
getFriendById(state){
return (id) => {
const friend = state.friends.find(item=>item.id == id)
return friend;
}
}
},
mutations: {
increment(state){
state.counter++
},
changeName(state){
state.name = "王小波"
},
changename(state,name){
state.name = name
},
changeLevel(state){
state.level++
},
// changeInfo(state,userInfo){
// state.name = userInfo.name;
// state.level = userInfo.level
// }
[CHANGE_INFO](state,userInfo){
state.name = userInfo.name;
state.level = userInfo.level
},
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)
},
async fetchHomeMultidataAction(context){
// // 1.返回promise,给promise设置then
// // fetch("http://123.207.32.32:8000/home/multidata").then(res=>{
// // return res.json().then(data=>{
// // console.log(data)
// // })
// // })
// // 2.promisel链式调用
// // fetch("http://123.207.32.32:8000/home/multidata").then(res=>{
// // return res.json()
// // }).then(data =>{
// // console.log(data)
// // })
// 3.await/async
const res = await fetch("http://123.207.32.32:8000/home/multidata")
const data = await res.json();
console.log(data);
// 修改state数据
context.commit("changeBanners",data.data.banner.list)
context.commit("changeRecommends",data.data.recommend.list)
return 'aaaa';
// // return new Promise(async (resolve,reject)=>{
// // const res = await fetch("http://123.207.32.32:8000/home/multidata")
// // const data = await res.json();
// // console.log(data);
// // // 修改state数据
// // context.commit("changeBanners",data.data.banner.list)
// // context.commit("changeRecommends",data.data.recommend.list)
// // // reject()
// // resolve("aaaa")
// // })
// }
}
})
export default store
- HomeCom.vue
<template>
<div>
<h2>Home Page</h2>
<ul>
<template v-for="item in $store.state.home.banners" :key="item.acm">
<li>{{ item.title }}</li>
</template>
</ul>
</div>
</template>
<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的基本使用
- store/index.js文件
import { createStore } from "vuex";
import { CHANGE_INFO } from "./mutation_types";
import homeModule from './modules/home'
const store = createStore({
state:() => ({
counter:100,
name:'why',
level:10,
users:[
{id:111,name:'why',age:20},
{id:112,name:'kobe',age:30},
{id:113,name:'james',age:25},
],
friends:[
{id:111,name:'why',age:20},
{id:112,name:'kobe',age:30},
{id:113,name:'james',age:25},
],
// // 服务器数据
// banners:[],
// recommends:[]
}),
getters:{
doubleCounter(state){
return state.counter * 2
},
totalAge(state){
return state.users.reduce((preValue,item)=>{
return preValue + item.age
},0)
},
message(state){
return `name:${state.name} level:${state.level}`
},
// 获取某一个frends,是可以返回函数的
getFriendById(state){
return (id) => {
const friend = state.friends.find(item=>item.id == id)
return friend;
}
}
},
mutations: {
increment(state){
state.counter++
},
changeName(state){
state.name = "王小波"
},
changename(state,name){
state.name = name
},
changeLevel(state){
state.level++
},
// changeInfo(state,userInfo){
// state.name = userInfo.name;
// state.level = userInfo.level
// }
[CHANGE_INFO](state,userInfo){
state.name = userInfo.name;
state.level = userInfo.level
},
// 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)
},
// async fetchHomeMultidataAction(context){
// // 1.返回promise,给promise设置then
// // fetch("http://123.207.32.32:8000/home/multidata").then(res=>{
// // return res.json().then(data=>{
// // console.log(data)
// // })
// // })
// // 2.promisel链式调用
// // fetch("http://123.207.32.32:8000/home/multidata").then(res=>{
// // return res.json()
// // }).then(data =>{
// // console.log(data)
// // })
// // 3.await/async
// const res = await fetch("http://123.207.32.32:8000/home/multidata")
// const data = await res.json();
// console.log(data);
// // 修改state数据
// context.commit("changeBanners",data.data.banner.list)
// context.commit("changeRecommends",data.data.recommend.list)
// return 'aaaa';
// // return new Promise(async (resolve,reject)=>{
// // const res = await fetch("http://123.207.32.32:8000/home/multidata")
// // const data = await res.json();
// // console.log(data);
// // // 修改state数据
// // context.commit("changeBanners",data.data.banner.list)
// // context.commit("changeRecommends",data.data.recommend.list)
// // // reject()
// // resolve("aaaa")
// // })
// }
},
modules:{
home:homeModule
}
})
export default store
- modules/home.js
export default{
state:()=>({
// 服务器数据
banners:[],
recommends:[]
}),
mutations:{
changeBanners(state,banners){
state.banners = banners
},
changeRecommends(state,recommends){
state.recommends = recommends
}
},
actions:{
async fetchHomeMultidataAction(context){
// 1.返回promise,给promise设置then
// fetch("http://123.207.32.32:8000/home/multidata").then(res=>{
// return res.json().then(data=>{
// console.log(data)
// })
// })
// 2.promisel链式调用
// fetch("http://123.207.32.32:8000/home/multidata").then(res=>{
// return res.json()
// }).then(data =>{
// console.log(data)
// })
// 3.await/async
const res = await fetch("http://123.207.32.32:8000/home/multidata")
const data = await res.json();
console.log(data);
// 修改state数据
context.commit("changeBanners",data.data.banner.list)
context.commit("changeRecommends",data.data.recommend.list)
return 'aaaa';
// return new Promise(async (resolve,reject)=>{
// const res = await fetch("http://123.207.32.32:8000/home/multidata")
// const data = await res.json();
// console.log(data);
// // 修改state数据
// context.commit("changeBanners",data.data.banner.list)
// context.commit("changeRecommends",data.data.recommend.list)
// // reject()
// resolve("aaaa")
// })
}
}
}
- HomeCom.vue
<template>
<div>
<h2>Home Page</h2>
<ul>
<template v-for="item in $store.state.home.banners" :key="item.acm">
<li>{{ item.title }}</li>
</template>
</ul>
</div>
</template>
<script setup>
import { useStore } from 'vuex';
// 进行vuex网络请求
const store = useStore()
store.dispatch("fetchHomeMultidataAction").then(res=>{
console.log("home中的then被回调:",res)
})
</script>
<style scoped>
</style>
Modules-默认模块化
Home.vue
<template>
<div>
<h2>Home Page</h2>
<h2>Counter模块的counter:{{ $store.state.counter.count }}</h2>
<h2>Counter模块的doubleCounter:{{ $store.getters.doubleCount }}</h2>
<button @click="incrementCount">count模块+1</button>
</div>
</template>
<script setup>
import { useStore } from 'vuex';
// 进行vuex网络请求
const store = useStore()
function incrementCount(){
store.dispatch("incrementCountAction")
}
</script>
<style scoped>
</style>
store/index.js文件
const counter = {
namespaced:true,
state:() =>({
count:99
}),
mutations:{
incrementCount(state){
state.count++
}
},
getters:{
doubleCount(state,getters,rootState){
return state.count + rootState.rootCounter
}
},
actions:{
incrementCountAction(context){
context.commit("incrementCount")
}
}
}
export default counter
修改模块子的值
HomeCom.vue
<template>
<div>
<h2>Home Page</h2>
<h2>Counter模块的counter:{{ $store.state.counter.count }}</h2>
<h2>Counter模块的doubleCounter:{{ $store.getters["counter/doubleCount"] }}</h2>
<button @click="incrementCount">count模块+1</button>
</div>
</template>
<script setup>
import { useStore } from 'vuex';
// 进行vuex网络请求
const store = useStore()
function incrementCount(){
store.dispatch("counter/incrementCountAction")
}
// module修改或派发根组件
// 如果我们希望在action中修改root中的state,那么有如下方式
// changeNameAction({commit,dispatch,state,rootState,getters,rootGetters}){
// commit("changeName","kobe");
// commit("changeNameRootName",null,{root:true});
// dispatch("changeRootNameAction",null,{root:true});
// }
</script>
<style scoped>
</style>
感谢观看,我们下次见