Vuex如何獲取getter對(duì)象中的值(包括module中的getter)
Vuex獲取getter對(duì)象中的值
getter取值與state取值具有相似性
1.直接從根實(shí)例獲取
// main.js中,把store注冊(cè)在根實(shí)例下,可使用this.$stroe.getters直接取值 computed: { ? testNum1() { ? ? return this.$store.getters.testNum1; ? } }
2.使用mapGetters取值
import { mapGetters } from "vuex"; export default { ? computed: { ? ? ...mapGetters({ ? ? ? // 把 `this.getNum1` 映射為 `this.$store.getters.getNum1` ? ? ? getNum1: "getNum1" ? ? }), ? ? ...mapGetters([ ? ? ? // 使用對(duì)象展開運(yùn)算符將 getter 混入 computed 對(duì)象 ? ? ? "getNum4" ? ? ]) ? } };
3.使用module中的getter
module中的getter,又分為namespaced(命名空間)為true和false的情況。默認(rèn)為false,則表示方位都是全局注冊(cè),與上邊兩種方法一致。
當(dāng)為true時(shí),則使用如下方法:
import { mapGetters } from "vuex"; export default { ? computed: { ? ? getNum1(a,b) { ? ? ? return this.$store.getters['moduleA/getNum1'] ? ? }, ? ? // 第一個(gè)參數(shù)是namespace命名空間,填上對(duì)應(yīng)的module名稱即可 ? ? ...mapGetters("moduleA", { ? ? ? getNum2: "getNum2" ? ? }), ? ? ...mapGetters("moduleA", ["getNum3"]) ? } };
計(jì)算屬性獲取的getter值需要刷新才能更新
描述
// state state: { leader: null }, // getters getters: { getLead: state => state.leader } // mutations mutations: { setLead (state, data) { state.leader = data } }, // 頁面中賦值 // 登錄時(shí)改變state.leader的值 this.$store.commit('setLead', true) // 組件中計(jì)算屬性監(jiān)聽 import { mapGetters } from 'vuex' computed: { leader () { ...mapGetters(['getLead']) } }
打印this.leader,直接獲取計(jì)算屬性值
刷新之后的打印結(jié)果
解決
增加監(jiān)聽函數(shù)watch,修改計(jì)算屬性
computed: { ...mapGetters(['getLead']) //原來 //leader () { // ...mapGetters(['getLead']) //} } watch: { // 監(jiān)聽getters數(shù)據(jù) --- 'getLead' // 解決state數(shù)據(jù)可以更新,但getters數(shù)據(jù)需要刷新才能更新的問題 getLead (val) { this.leader = val // this.leader是data中自定義的值, // 賦值之后,一定要重寫之后的方法, // 不然只是取值,頁面操作依然不會(huì)改變 this.showVip() // 這是我頁面上的方法名 } },
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue中的非父子間的通訊問題簡(jiǎn)單的實(shí)例代碼
這篇文章主要介紹了vue中的非父子間的通訊問題簡(jiǎn)單的實(shí)例代碼,需要的朋友可以參考下2017-07-07vue文件批量上傳及進(jìn)度條展示的實(shí)現(xiàn)方法
開發(fā)項(xiàng)目的時(shí)候,用到文件上傳的功能很常見,包括單文件上傳和多文件上傳,下面這篇文章主要給大家介紹了關(guān)于vue文件批量上傳及進(jìn)度條展示的實(shí)現(xiàn)方法,需要的朋友可以參考下2022-12-12vue的style綁定background-image的方式和其他變量數(shù)據(jù)的區(qū)別詳解
今天小編就為大家分享一篇vue的style綁定background-image的方式和其他變量數(shù)據(jù)的區(qū)別詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-09-09