VueWeb前端之路让前端飞

我对vuex的理解(二) 之 mapGetters取值和mapM

2017-08-17  本文已影响5482人  ComfyUI

前言:最近在做一个vue的项目,碰到一点关于mapMutations传参的问题,解决完问题了所以写一下对它理解。

1、官网中的提交载荷(传参)具体到一般demo中大概是这样的

const store new Vuex.Store({
    state: {
        count: 0
    },
    mutations: {
        increment(state,n){
            state.count += n
        }
    }
})

new Vue({
    el:"#app",
    store,
    computed: {
        count() {
           return store.state.count
        }
    },
    methods: {
        add() {
           //传参
           store.commit('increment',10) 
        }
    }
})

2、具体到项目中,用mapMutations辅助函数的传参

//store.js
import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

//定义state,并将listName设置为一个空对象
const state = {
    listName: {}
}
//定义mutations,可以传参,用于设置state里的listName
const mutations = {
    set_listname: (state,value) => {
        state.listName=value
    }
}
//定义getters,用于获取出state里的对象
const getters = {
    get_listname: state => {
        return state.listName
    }
}

export default new Vuex.Store({
    getters,
    state,
    mutations
})
//main.js
import Vue from 'vue'
import App from './App'
import store from './store'

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  template: '<App/>',
  components: { App }
})
//App.vue
import {mapMutations} from 'vuex'

export default {
  //定义一个listName,作为下面的mapMutations的传参参数,修改state的listName
  data() {
    listName: {
      name:'Ewall',
      age:'21'
    }
  },
  created (){
    //调用set_listname方法,将listName对象作为参数传入
    this.set_listname(listName)
  },
  methods: {
    ...mapMutations(['set_listname'])
  },
  
}
//app-child.vue
 import {mapGetters} from 'vuex'

  export default {
      computed: {
      //获取state里面的listName对象
          ...mapGetters(['get_listname'])
      },
      created() {
      //打印下获得数据结果
          console.log(this.get_listname)
      }
  }

参考: https://vuex.vuejs.org/zh-cn/mutations.html

上一篇下一篇

猜你喜欢

热点阅读