从组件中的 mapActions 向 vuex store 传递值

Pass value to vuex store from mapActions in component

我如何从我的 Vuex 商店访问我的 @click partSelect 中的值。

Vue 模板

<div id="currentPart">
    <img id="modelImg" @click="partSelect('modelOne')" class="modelImg" :src="model[0]"/>
    <img id="modelImg2" @click="partSelect('modelTwo')" class="modelImg" :src="model[1]"/>
    <img id="modelImg3" @click="partSelect('modelThree')" class="modelImg" :src="model[2]"/>
  </div>

Javascript 映射操作

<script> 
 methods: mapActions([
    'getImage',
    'getImageAsync',
    'partSelect'
  ]),
</script>

Vuex Javascript

export const partSelect = ({ commit }) => commit('partSelect')

这其实很简单,Vuex 中的动作应该是这样的:

export const partSelect = ({ commit }, myString) => {
    // do something with myString
    commit('partSelectMutation') // execute the mutation
    // if the data should be added to the mutation:
    // commit('partSelectMutation', { myString })
}

访问 mutation 中的变量 myString(如果使用上面的第二个版本):

mutations: {
    partSelectMutation: (state, { myString }) => {
         state.myString = myString
    },
    //...
}

将映射操作作为事件回调的简单示例:

var store = new Vuex.Store({
  state: {
    content: 'Old content'
  },
  mutations: {
    updateContent (state, payload) {
      state.content = payload
    }
  },
  actions: {
    mapMe (context, payload) {
      context.commit('updateContent', payload)
    }
  }
})

new Vue ({
  el: '#app',
  store,
  computed: {
    content () {
      return this.$store.state.content
    }
  },
  methods: Vuex.mapActions({
    mappedAction: 'mapMe'
  })
})
<div id="app">
  {{ content }}<br>
  <button @click="mappedAction('New content')">Click</button>
</div>

<script src="https://unpkg.com/vue"></script>
<script src="https://unpkg.com/vuex"></script>

这对我有用:

const mutations = {
    myrequest (state, id) {
        console.log("id:" + id);
    }
}    
const actions = {
    myrequest ({ commit }, id) {
        commit('myrequest', id)
    }
}