日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 Vue 正文

詳解Vuex中getters的使用教程_vue.js

作者:IT利刃出鞘 ? 更新時間: 2022-04-09 Vue

簡介

說明

本文用示例介紹Vuex的五大核心之一:getters。

官網

Getter | Vuex

API 參考 | Vuex

getters概述

說明

getters 是Store的計算屬性,可以對State進行計算操作。就像計算屬性一樣,getter 的返回值會根據它的依賴被緩存起來,且只有當它的依賴值發生了改變才會被重新計算。

雖然組件內也可以做計算屬性,但getters 可以在多組件之間復用。如果一個狀態只在一個組件內使用,可以不用getters。

來源

有時我們需要從 store 中的 state 中派生出一些狀態,例如對列表進行過濾并計數:

computed: {
  doneTodosCount () {
    return this.$store.state.todos.filter(todo => todo.done).length
  }
}

如果有多個組件需要用到此屬性,我們要么復制這個函數,或者抽取到一個共享函數然后在多處導入它(無論哪種方式都不是很理想)。getter就是為了解決這個問題而產生的。

用法

直接使用

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>計數器的值:{{thisCount}}</div>
    <div>計數器的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

原文鏈接:https://blog.csdn.net/feiying0canglang/article/details/122724236

欄目分類
最近更新