【问题标题】:vue.js : error unknown action type?vue.js:错误未知动作类型?
【发布时间】:2018-07-20 01:58:00
【问题描述】:

我创建了我的商店 store/user.js

export const state = () => ({
      user: {},
    });
export const mutations = {

};
export const actions = {
  AUTH ({commit},{email, password}){
console.log('email, password =', email, password)
  }
};

export const getters = {};

组件:

<template>
<form @submit.prevent="AUTH(model)">
  <input type="text"  required v-model.lazy = "model.email">
    <input type="password" required v-model.lazy = "model.password" >
</template>


<script>
  import { mapActions } from 'vuex'

  export default {

    data() {
      return {
        model:{
          email:" " ,
          password:" "

      }

      }
    },
    methods: {
      ...mapActions(['AUTH']),
}
}

在我的组件中,我试图从一个模块中执行一个 vuex 操作,但我得到了一个错误,即使这个操作被定义了:

unknown action type: AUTH,

我对问题一无所知。

index.js

import Vue from 'vue'
import Vuex from 'vuex'

import user from './modules/user.js'

Vue.use(Vuex);

const store = new Vuex.Store({
  modules: {
    user
  }
})

【问题讨论】:

  • 您能提供您创建商店的代码吗?你在使用 vuex 模块吗?
  • 因为您使用的是模块,所以它将是namespaced。见this answer
  • [nuxt] store/index.js 应该导出一个返回 Vuex 实例的方法。我错了
  • 在 Nuxt 中使用模块模式时,您无需自己创建商店。相反,导出状态、getter、突变和动作。
  • 我使用 nuxt 。怎么办?

标签: javascript vue.js nuxt.js


【解决方案1】:

你需要使用createNamespacedHelpers:

import { createNamespacedHelpers } from 'vuex'

const { mapState, mapActions } = createNamespacedHelpers('users')

Binding helpers with namespace

否则,映射助手需要完整的模块命名空间:

...mapActions([
  'users/AUTH'
])

// if you are only using one module in the component
...mapActions('users', [
  'AUTH'
])

Nuxt

您正在混合经典模式和模块模式。使用模块模式时,Nuxt 从index.js 文件创建存储实例。您只需导出状态、getter、突变和操作。状态应该作为函数导出:

export const state = () => ({
  foo: 0,
  bar: 1
})

store 目录中的任何文件都将被视为一个模块,Nuxt 将自动将其注册为命名空间模块。

- store
-- index.js // the store
-- users.js // module 'users'
-- foo.js // module 'foo'

用户模块看起来是正确的。

对您的组件进行以下更改:

// template
<form @submit.prevent="submitForm">

// script
methods: {
    ...mapActions({
         auth: 'users/AUTH'
    }),
    submitForm () {
        this.auth(this.model)
    }
}

【讨论】:

  • 我得到错误 Uncaught TypeError: _vm.AUTH is not a function
  • 尝试使用this.$store.dispatch('users/AUTH')
  • 并且属性或方法“AUTH”未在实例上定义,但在渲染期间被引用。
  • 我修复但得到 fn.bind 不是函数。
  • 我没有看到您发布的任何代码中使用了bind
猜你喜欢
  • 2018-06-03
  • 2022-01-02
  • 1970-01-01
  • 2023-02-21
  • 2020-07-14
  • 2019-03-13
  • 2017-12-27
  • 1970-01-01
  • 2022-06-28
相关资源
最近更新 更多