• vuex 进阶 mapState mapGetter mapActions mapMutations


    1 说明

    mapStatemapGetter  获取stategetters;mapStatemapGetter是映射为计算属性=>获取数据(方便简洁写法)

    mapMutationsmapActions方便操作mutationsactions方法  ;mapMutationsmapActions是映射为组件methods方法=>修改数据

    2使用

    state/index.js

    import Vue from 'vue'
    import Vuex from 'vuex'
    Vue.use(Vuex)
    export default new Vuex.Store({
      state: { //存放状态
        nickname:'Simba',
        firstname:'张',
        lastname:'三丰',
        age:20,
        gender:'男',
        money:1000
      },
      getters:{
    //
    getters相当于vue中的计算属性,通过getters进一步处理,得到我们想要的值,而且允许传参,第一个参数就是state
        realname(state){ return state.firstname+state.lastname },
    money_us(state){ return (state.money/7).toFixed(2) }
    },
    mutations:{
      addAge(state,payLoad){
         state.age+=payLoad.number
      }

    }
     
     
    })

     1引入

    import {mapState,mapGetter,mapActions,mapMutations} from 'vuex'

    2 使用

    组件内
    computed: {   //computed是不能传参数的
      value(){
       return this.val/7
      },
      ...mapState(['nickname','age','gender'])
      ...mapGetters(['realname','money_us'])

    //相当于

    //nickname(){return this.$store.state.nickname}
    //age(){return this.$store.state.age}
    //gender(){return this.$store.state.gender}
    }
    html中使用
    <div>{{nickName}}:{{age}}</div>
    <div>{{
    realname}}</div>



    mutations需要通过commit来调用其里面的方法,它也可以传入参数,第一个参数是state,第二个参数是载荷(payLoad),也就是额外的参数
    子组件

       //参数我们可以在调用这个方法的时候写入

    //注意  方法名称保持一致

    <button @click="addAge({number:5})">测试</button>
    methods:{
     ...mapMutations(['addAge'])
       //相当于 
       addAge(){
       //调用的时候第二个参数最好写成对象形式,这样我们就可以传递更多信息。
         this.$store.commit('addAge',{
           number:5
         })
    }


    }
     
  • 相关阅读:
    POJ 1611 : The Suspects (普通并查集)
    深入解析 Dubbo 3.0 服务端暴露全流程
    智能搜索推荐一体化营收增长解决方案
    云上应用系统数据存储架构演进
    EMR on ACK 全新发布,助力企业高效构建大数据平台
    介绍一下闭包和闭包常用场景?
    BFC
    高斯消元学习笔记
    云虚拟主机如何设置域名解析
    Centos7.3安装openJDK
  • 原文地址:https://www.cnblogs.com/fanjiawen/p/14486195.html
Copyright © 2020-2023  润新知