詳解Vuex中getters的使用教程
簡介
說明
本文用示例介紹Vuex的五大核心之一:getters。
官網(wǎng)
getters概述
說明
getters 是Store的計算屬性,可以對State進行計算操作。就像計算屬性一樣,getter 的返回值會根據(jù)它的依賴被緩存起來,且只有當它的依賴值發(fā)生了改變才會被重新計算。
雖然組件內也可以做計算屬性,但getters 可以在多組件之間復用。如果一個狀態(tài)只在一個組件內使用,可以不用getters。
來源
有時我們需要從 store 中的 state 中派生出一些狀態(tài),例如對列表進行過濾并計數(shù):
computed: {
doneTodosCount () {
return this.$store.state.todos.filter(todo => todo.done).length
}
}
如果有多個組件需要用到此屬性,我們要么復制這個函數(shù),或者抽取到一個共享函數(shù)然后在多處導入它(無論哪種方式都不是很理想)。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

到此這篇關于詳解Vuex中getters的使用教程的文章就介紹到這了,更多相關Vuex getters內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
element-ui?table表格控件實現(xiàn)單選功能代碼實例
這篇文章主要給大家介紹了關于element-ui?table表格控件實現(xiàn)單選功能的相關資料,單選框是指在?Element?UI?的表格組件中,可以通過單選框來選擇一行數(shù)據(jù)。用戶只能選擇一行數(shù)據(jù),而不能同時選擇多行,需要的朋友可以參考下2023-09-09
Vue中this.$router和this.$route的區(qū)別及push()方法
這篇文章主要給大家介紹了關于Vue中this.$router和this.$route的區(qū)別及push()方法的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-05-05
Vite3 Svelte3構建Web應用報錯process is not def
這篇文章主要介紹了Vite3 Svelte3構建Web應用報錯:'process is not defined'解決方法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-06-06

