vue3+vuex 的 getters 的 使用
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 参数1:state的 想修改state必须通过mutations来修改
mutations: {
},
actions: {
},
modules: {
}
})
app.vue <template> <div class="app"> <h3>在模板中直接使用(vue2-3都可用)</h3> 计算 : {{ $store.getters.counterGetter }} <br/> 年龄 : {{ $store.getters.usersAgesGetter}} <br/> 信息 : {{ $store.getters.message}} <br/> <!-- 根据id或者某一个朋友的信息 --> 朋友的信息 : {{ $store.getters.firendId(111) }} <h3>vue3的写法</h3> 计算 : {{counterGetter}} <br/> 年龄 : {{usersAgesGetter}} <br/> 信息 : {{message}} <br/> <!-- 根据id或者某一个朋友的信息 --> 朋友的信息 : {{firendId(111)}} <br/> </div> </template> <script setup> import { toRefs ,computed} from 'vue'; import { useStore } from 'vuex'; const store = useStore() // 直接对 store.state 进行解构 => 不是响应式 // 使用 toRefs 对齐响应式 const {counterGetter,usersAgesGetter,firendId} = toRefs(store.getters) // 针对某一个getters属性适用computed const message = computed(()=>store.getters.message) </script>
本文来自博客园,作者:杨建鑫,转载请注明原文链接:https://www.cnblogs.com/qd-lbxx/p/16636642.html

浙公网安备 33010602011771号