vue3.0如何使用computed來獲取vuex里數(shù)據(jù)
vue3使用computed獲取vuex里數(shù)據(jù)
不再是vue2.0里什么mapGetter,mapState那些復(fù)雜的獲取方式,
vue3.0里直接使用computed就可以調(diào)用vuex里的數(shù)據(jù)了。喜大普奔。
同時注意,一點,不可以直接使用useStore()方法里的state對象,因為在輸出useStore方法的數(shù)據(jù)中,state是淺灰色的。
淺灰色只可看到,但是不可以直接使用。
如圖:

<template>
<div>{{dataList}}</div>
</template>
<script>
import { defineComponent, ref, reactive, toRefs, computed } from "vue";
import { useStore } from 'vuex'
// computed 計算屬性
export default defineComponent({
name: "home",
setup(props, ctx) {
let store = useStore()
// 因為store里state是淺灰色的,所以不能直接使用,若要使用store.state.dataList需要computed來調(diào)用
console.log(store)
let dataList = computed(()=>{
return store.state.dataList
})
console.log(dataList)
return {
store,
dataList
}
},
});
</script>
<style scoped lang="scss">
</style>
vue3 簡單使用vuex
mutations用于更變store中的數(shù)據(jù)(同步)

如何調(diào)用mutations中數(shù)據(jù)

vue3中取vuex里的數(shù)據(jù) 需要用 computed獲取
使用store.commit(“add”) 來觸發(fā)vuex里的mutations方法
觸發(fā)mutations時傳遞參數(shù):store.commit(“addN”,2) 通過第二個參數(shù)

使用action觸發(fā)某個mutation

使用dispatch

如何使用getters
getter用于對store中的數(shù)據(jù)進行加工處理形成的新的數(shù)據(jù)
不會修改store中的原數(shù)據(jù) 它只起到一個包裝器的作用 將store中的數(shù)據(jù)變一種形式返回出來
1.getter可以對store中已有的數(shù)據(jù)加工處理之后形成新的數(shù)據(jù),類似vue的計算屬性
2.store中數(shù)據(jù)發(fā)生改變 getter中的數(shù)據(jù)也會跟著變化

用計算屬性可以獲取vuex中的getters中的數(shù)據(jù)

總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
Vue嵌套iframe時$router.go(-1)后退bug的原因解析
這篇文章主要介紹了Vue嵌套iframe,$router.go(-1)后退bug的問題原因及解決方法,本文給大家分享問題原因所在及解決方案,需要的朋友可以參考下吧2023-09-09

