首页 > 其他 > 详细

vuex 配置 getters

时间:2020-04-13 19:50:39      阅读:53      评论:0      收藏:0      [点我收藏+]

在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>

 

vuex 配置 getters

原文:https://www.cnblogs.com/caoleyun/p/12693149.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!