搜尋

首頁  >  問答  >  主體

javascript - vuex到底如何在頁面上呼叫actions?

頁面程式碼

methods: {
    ...mapActions(['addList', 'delList']),
    add (value) {
      this.addList({title: value})
    },
    del (item) {
      this.delList(item)
    }
}

actions中程式碼

import * as types from './mutations'
export const addList = ({commit}, item) => {
  commit(types.ADD_LIST, item)
}    
export const delList = ({commit}, item) => {
  commit(types.DELETE_LIST, item)
}

但是執行會報[vuex] Expects string as the type, but found function.求高手指點一下哪裡出錯了,非常感謝.
如果把上面程式碼改為下面的程式碼就可以執行

methods: {
    add (value) {
      this.$store.commit('ADD_LIST', {title: value})
    },
    del (item) {
      this.$store.commit('DELETE_LIST', item)
    }
}
我想大声告诉你我想大声告诉你2857 天前814

全部回覆(3)我來回復

  • 黄舟

    黄舟2017-05-19 10:41:52

    methods: {
        add (value) {
          this.$store.commit('ADD_LIST', {title: value})
        },
        del (item) {
          this.$store.commit('DELETE_LIST', item)
        }
    }

    問一下,你說這段程式碼可以執行達到效果,那為什麼不是this.$store.commit(types.DELETE_LIST, item)?

    你actions.js中都用了types,是不是mutation-types.js檔案出了問題呢?

    回覆
    0
  • 伊谢尔伦

    伊谢尔伦2017-05-19 10:41:52

    export const addList = (commit) => (item) => {
      commit(types.ADD_LIST, item)
    } 
    

    沒用過vuex,不過如果跟Redux差不多的話,應該是這麼用。

    回覆
    0
  • 黄舟

    黄舟2017-05-19 10:41:52

    找到問題的答案了,感謝樓上的提醒,actions.js檔案應該改成下面這樣

    export const addList = ({commit}, item) => {
      commit('ADD_LIST', item)
    }    
    export const delList = ({commit}, item) => {
      commit('DELETE_LIST', item)
    }

    或還是用之前的寫法,但要新建一個mutation-types.js檔

    export const ADD_LIST = 'ADD_LIST'
    export const DELETE_LIST = 'DELETE_LIST'

    actions.js

    import * as types from './mutation-types'
    export const addList = ({commit}, item) => {
      commit(types.ADD_LIST, item)
    }    
    export const delList = ({commit}, item) => {
      commit(types.DELETE_LIST, item)
    }

    回覆
    0
  • 取消回覆