vuex 配置 getters


在store中如果有依賴於state的值而改變的,相當於是store的computed,此時可以在store中增加一個getters配置項:

store.js

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);
const store = new Vuex.Store({
    //這里的state必須是JSON,是一個對象。
    state: {
        count: 0 ,        //這里就是初始值的羅列,
        student : [
            {"name" : "小1" , "sex" : "男" },
            {"name" : "小2" , "sex" : "女" },
            {"name" : "小3" , "sex" : "男" },
            {"name" : "小4" , "sex" : "女" }
        ]
    },
    //突變,羅列所有可能改變state的方法
    mutations: {
        //沒有所謂的大寫字母的Type了,就是一個一個函數
        add (state) {
              state.count++;
        },
        minus (state) {
            state.count--;
        }
    },
    getters : { nansheng : state => {
            return state.student.filter((item)=>{
                return item.sex == "男"; }) } }
});

export default store;

組件中使用this.$store.getters.**來獲得這個值。

<style scopoed>
 
</style>

<template>
    <div>
        我是子組件
        <h1>
            <button v-on:click="minusnandler">減少</button>
            {{count}}
            <button v-on:click="addhandler">增加</button>
        </h1>
        <h1>
            {{nansheng}}
        </h1>
    </div>
</template>

<script>
    export default {
        data(){
            return {
                m : 6
            }
        },
        computed : {
            count(){
                return this.$store.state.count;
            },
            nansheng (){
                return this.$store.getters.nansheng;
            }
        },
        methods : {
            addhandler(){
                this.$store.commit("add");
            },
            minusnandler(){
                this.$store.commit("minus");
            }
        }
    }
</script>

 


免責聲明!

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



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