2017-04-11 57 views
3

我VUE組分是這樣的:如何更新vuex中的狀態? vue.js 2

<template> 
    <div> 
     <div class="row"> 
      <div class="col-sm-3"> 
       <div class="form-group"> 
        <label for="status" class="sr-only">Status</label> 
        <select class="form-control" v-model="selected" @change="filterByStatus()"> 
         <option value="">All Status</option> 
         <option v-for="status in orderStatus" v-bind:value="status.id">{{ status.name }}</option> 
        </select> 
       </div> 
      </div> 
     </div> 
     ... 
    </div> 
</template> 

<script> 
    import { mapActions, mapGetters } from 'vuex'; 
    export default { 
     ... 
     data() { 
      return { selected: '' } 
     }, 
     methods: { 
      filterByStatus: function() { 
       this.$store.state.status = this.selected 
      } 
     } 
    } 
</script> 

我的模塊訂購vuex是這樣的:

import { set } from 'vue' 
import order from '../../api/order' 
import * as types from '../mutation-types' 

const state = { 
    status: '' 
} 
const getters = { 
    ... 
} 
const actions = { 
    ... 
} 

const mutations = { 
    ... 
} 

export default { 
    state, 
    getters, 
    actions, 
    mutations 
} 

我使用此:this.$store.state.order.status = this.selected,當被執行時,更新的狀態,但存在着像這樣的錯誤:

[Vue warn]: Error in callback for watcher "function() { return this._data.$$state }": (found in)

Error: [vuex] Do not mutate vuex store state outside mutation handlers.

我該如何解決它?

我想更新的狀態,因爲我想通過組件使用的值的另一

回答

5

您一定已經收到,因爲在你的vuex存儲設立使strict mode的這個錯誤。

但是,這是一個很好的做法。除了突變之外,您不得修改狀態。

所以要使用新設置的商店;有一個突變,如:

const mutations = { 
    mutateOrderStatus: function (state, payload) { 
     state.order.status = payload 
    } 
} 

const actions = { 
    updateOrderStatusAction: function ({commit}, payload) { 
     commit('mutateOrderStatus', payload) 
    } 
} 

現在包括在您的組件,如:

... 
methods: { 
    ...mapActions([ // spread operator so that other methods can still be added. 
    'updateOrderStatusAction' 
    ]), 
    filterByStatus: function() { 
    this.updateOrderStatusAction(this.selected) 
    } 
} 

注意:您可能需要babel並安裝到使用蔓延運營商的babel-preset-es2015...