vuex學習---getters


vue是一個面向數據,只有一個層:view,在數據傳給客戶端之前,計算其相關的屬性,應該是什么樣子,前面有個mapState([])遠程加載數據,加載的是一個靜態的數據,如果想獲取動態的數據,就要用到 getters 。官方建議在getter和computed不推薦使用箭頭函數。

這個例子依舊沿用了之前vuex學習---簡介的模板

1.首先在store.js中

   一開始會在頁面上顯示 :104 常量值4+ getters中的100   ;點擊加 會104+ 100+3 ,變成207 ;點擊減207+100-1 = 306 ,依次如此。  

 1 import Vue from 'vue'
 2 import Vuex from 'vuex'
 3 
 4 //使用vuex模塊
 5 Vue.use(Vuex);
 6 
 7 //聲明靜態常量為4
 8 const state = {
 9     count : 4
10 };
11 
12 //定義一個方法,在vue中,唯一的定義狀態的方法就是提交一個mutations,
13 //而且導出時,只要導出mutations即可,
14 //當使用時,也僅僅只要使用統一的 $store.commit('event') event是事件名稱。
15 const mutations = {
16     add(state,n){
17         state.count +=n.a;
18     },
19     sub(state){
20         state.count--;
21     }
22 };
23 //定義getters 不推薦使用箭頭函數
24 const getters = {
25   count:function(state){
26       return state.count +=100
27   }
28 };
29 
30 //導出一個模塊
31 export default new Vuex.Store({
32     state,
33     mutations,
34     getters
35 })

 

2. 在App.vue中

<template>
  <div id="app">
     <div id="appaaa">
        <h1>這是vuex的示例</h1>

        <p>調用倉庫常量 {{$store.state.count}}</p>
        <!-- <p>組件內部count{{count111}}</p> -->
        <p>組件內部count{{count}}</p>
        <p>
            <button @click = "$store.commit('add',{a:3})">加</button>
            <button @click = "sub">減</button>
        </p>
    </div>
  </div>
</template>

<script>
//引入mapGetters 
import {mapState,mapMutations,mapGetters} from 'vuex'
export default {
  name:'app',
  data(){
      return {
         
      }
  },
 computed:{
/*
...mapState
對於getters這段代碼是不需要的,這個是為了
<button @click = "$store.commit('add',{a:3})">加</button>
*/
...mapState([ 
"count"
         ]),
     // count(){
     //     return this.$store.getters.count;
     // }
      ...mapGetters([
          "count" ])
 },
 methods:mapMutations([
      'add',
      'sub'
     ]) 

}
</script>

<style>

</style>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM