詳解Vuex中g(shù)etters的使用教程
簡介
說明
本文用示例介紹Vuex的五大核心之一:getters。
官網(wǎng)
getters概述
說明
getters 是Store的計算屬性,可以對State進行計算操作。就像計算屬性一樣,getter 的返回值會根據(jù)它的依賴被緩存起來,且只有當(dāng)它的依賴值發(fā)生了改變才會被重新計算。
雖然組件內(nèi)也可以做計算屬性,但getters 可以在多組件之間復(fù)用。如果一個狀態(tài)只在一個組件內(nèi)使用,可以不用getters。
來源
有時我們需要從 store 中的 state 中派生出一些狀態(tài),例如對列表進行過濾并計數(shù):
computed: {
doneTodosCount () {
return this.$store.state.todos.filter(todo => todo.done).length
}
}
如果有多個組件需要用到此屬性,我們要么復(fù)制這個函數(shù),或者抽取到一個共享函數(shù)然后在多處導(dǎo)入它(無論哪種方式都不是很理想)。getter就是為了解決這個問題而產(chǎn)生的。
用法
直接使用
this.$store.getters.計算屬性名 // 不分模塊 this.$store.getters['模塊名/計算屬性名'] // 分模塊
mapGetters
import { mapGetters } from 'vuex'
export default {
computed: {
// 不分模塊
...mapGetters(['計算屬性名'])
// 分模塊,不重命名計算屬性
...mapGetters('模塊名', ['計算屬性名'])
// 分模塊,重命名計算屬性
...mapGetters('模塊名', {'新計算屬性名': '舊計算屬性名'})
}
}
示例
代碼
CouterStore.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const counterStore = new Vuex.Store(
{
state: {
count: 10
},
getters: {
doubleCount(state) {
return state.count * 2;
}
}
}
);
export default counterStore;
Parent.vue
<template>
<div class="outer">
<h3>父組件</h3>
<component-b></component-b>
</div>
</template>
<script>
import ComponentB from "./ComponentB";
export default {
name: 'Parent',
components: {ComponentB},
}
</script>
<style scoped>
.outer {
margin: 20px;
border: 2px solid red;
padding: 20px;
}
</style>
ComponentB.vue
<template>
<div class="container">
<h3>ComponentB</h3>
<div>計數(shù)器的值:{{thisCount}}</div>
<div>計數(shù)器的2倍:{{thisDoubleCount}}</div>
</div>
</template>
<script>
export default {
computed:{
thisCount() {
return this.$store.state.count;
},
thisDoubleCount() {
return this.$store.getters.doubleCount;
},
}
}
</script>
<style scoped>
.container {
margin: 20px;
border: 2px solid blue;
padding: 20px;
}
</style>
路由(router/index.js)
import Vue from 'vue'
import Router from 'vue-router'
import Parent from "../components/Parent";
Vue.use(Router)
export default new Router({
routes: [
{
path: '/parent',
name: 'Parent',
component: Parent,
}
],
})
測試
訪問:http://localhost:8080/#/parent

到此這篇關(guān)于詳解Vuex中g(shù)etters的使用教程的文章就介紹到這了,更多相關(guān)Vuex getters內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解vue.js數(shù)據(jù)傳遞以及數(shù)據(jù)分發(fā)slot
本篇文章給大家通過代碼實例分析了vue.js數(shù)據(jù)傳遞以及數(shù)據(jù)分發(fā)slot的相關(guān)知識,有這方面興趣的朋友參考下吧。2018-01-01
vue radio單選框,獲取當(dāng)前項(每一項)的value值操作
這篇文章主要介紹了vue radio單選框,獲取當(dāng)前項(每一項)的value值操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-09-09
vue3??mark.js?實現(xiàn)文字標(biāo)注功能(案例代碼)
這篇文章主要介紹了vue3??mark.js?實現(xiàn)文字標(biāo)注功能,本文通過實例代碼給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-09-09
vue開發(fā)中如何在js文件里使用pinia和組件同步
在JavaScript文件中封裝涉及到使用Pinia的方法時,發(fā)現(xiàn)Pinia和組件內(nèi)容并不同步,二者的狀態(tài)是獨立的,解決辦法是,在新建對象的時候,將Pinia作為參數(shù)傳入,本文給大家介紹vue開發(fā)中如何在js文件里使用pinia和組件同步,感興趣的朋友一起看看吧2024-10-10
Vue中組件(Component)和插件(Plugin)的區(qū)別及說明
這篇文章主要介紹了Vue中組件(Component)和插件(Plugin)的區(qū)別及說明,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2025-04-04

