vue3+vuex 的 actions 的 使用
<template> <div class="app"> 姓名:{{$store.state.nameVuex}} <button @click="btn">基本方法 : 修改名字</button> <br/> <button @click="btn1">传递值 : 修改名字</button> <h3>方法(映射状态) : 只适合vue2</h3> <button @click="changgeNameAction">基本方法 : 修改名字</button> <br/> <button @click="changgeName1Action('传递值')">传递值 : 修改名字</button> </div> </template> <script setup> import { useStore, mapActions } from 'vuex' const store = useStore() // 1.在setup中使用mapActions辅助函数 const actions = mapActions(["changgeNameAction", "changgeName1Action"]) const newActions = {} Object.keys(actions).forEach(key => { newActions[key] = actions[key].bind({ $store: store }) }) const { changgeNameAction, changgeName1Action } = newActions // 2.使用默认的做法 function btn() { store.dispatch("changgeNameAction") } function btn1() { store.dispatch("changgeName1Action",'任意值') } </script>
import { createStore } from 'vuex'
export default createStore({
state: {
nameVuex:'yjx',
levelVuex:100,
avtarURLVuex:'http',
counterVuex:100,
friends:[
{id:111,name:'why0',age:20},
{id:112,name:'why1',age:30},
{id:113,name:'why2',age:26}
]
},
// 计算属性 参数1:state 参数2:getters
getters: {
// 基本使用
counterGetter(state){
return state.counterVuex * 2
},
usersAgesGetter(state){
return state.friends.reduce((pre,item)=>{
return pre+item.age
},0)
},
// 使用其他的getters : 采用参数2
message(state,getters){
return `名字:${ state.nameVuex } , 等级 :${ state.levelVuex} , 朋友年龄总和 ${getters.usersAgesGetter}`
},
// 获取某id的朋友
firendId(state){
return function(id){
return state.friends.find(item=>item.id === id)
}
}
},
// mutations : 想修改state的值必须通过mutations来修改
// mutations 参数1:state的 参数2.传递过来的数据
mutations: {
changgeName(state){
state.nameVuex = '吴宇腾'
},
changgeName1(state,payload){
state.nameVuex = payload
}
},
// 参数1:context 参数2:传递过来的
//可以通过context.state来获取state
//可以通过context.getters来获取getters,
//可以通过context.commit('') 来提交mutations
//发送请求,都是在actions里面的
actions: {
changgeNameAction(context){
context.commit('changgeName')
},
changgeName1Action(context,payload){
context.commit('changgeName1',payload)
}
},
modules: {
}
})
本文来自博客园,作者:杨建鑫,转载请注明原文链接:https://www.cnblogs.com/qd-lbxx/p/16638561.html

浙公网安备 33010602011771号