【问题标题】:Vuex and form handling using v-model使用 v-model 处理 Vuex 和表单
【发布时间】:2019-11-09 17:17:31
【问题描述】:

我正在关注 vuex 表单处理的官方 vuex 教程:https://vuex.vuejs.org/guide/forms.html。我基本上复制粘贴了他们建议的 Two-way Computed Property 在底部的实现,但我仍然收到一个错误,说它无法读取未定义的属性“名称”:

[Vue warn]: Error in render: "TypeError: Cannot read property 'name' of undefined"

found in

---> <CustomForm> at src/components/Form.vue
       <Register> at src/views/Register.vue
         <App> at src/App.vue
           <Root>

Form.vue:

<custom-input title="Name" v-model="name" placeholder="Name" required />
computed: {
    name: {
      get () {
        return this.$store.state.form.name
      },
      set (value) {
        this.$store.commit('updateForm', ('name', value))
      }
    }

我尝试在 get 函数中的 return 语句之前console.log(this.$store.state.form.name),但没有打印出来

【问题讨论】:

    标签: vue.js vuex


    【解决方案1】:

    如果您想要一个可以更新您的 state.form 对象上的任何值的突变,那么我会做这样的事情。

    在mutation中,使用key将值赋给正确的属性

      mutations: {
        updateForm (state, {key, value}) {
          state.form[key] = value;
        }
      }
    

    并且在提交中,使用一个对象作为具有键和值参数的有效负载

    computed: {
        name: {
          get () {
            return this.$store.state.form.name
          },
          set (value) {
            this.$store.commit('updateForm', {key:'name', value});
          }
        }
    

    【讨论】:

    • 我的变异看起来像这样:updateForm: (state, key, value) =&gt; ({ ...state.form, [key]: value })。我想让它对每个输入字段都可重用,但我不确定它是否有效,好点!然而,这与我的问题无关,我可以注释掉 Form.vue 中的 set 函数并且仍然得到相同的错误。
    • 很遗憾你不能这样做,你可以传递只有一个有效载荷参数。有关如何在有效负载中使用多个参数,请参阅答案(第 2 部分)。
    • 感谢您提供的信息,我将改用您建议的方法!
    • 更新的答案只包含答案的相关部分
    【解决方案2】:
        You can use mapFields to enable to way data binding
          computed: {
            ...mapFields({
              firstName: 'form.name',
              lastName: 'form.lastName',
              phoneNumber: 'form.phoneNumber',
              emailAddress: 'form.emailAddress'
            }),
          },
    

    将此添加到您的突变中 从 'vuex-map-fields' 导入 { updateField };

    There is no need to add mutations to update the state this this done directly and using v-model you can bind these properties.
    

    【讨论】:

    • 这个包是节省生命和时间的。我在 Nuxt 项目中使用。让我很高兴,因为我在项目中有超过 45 个表格。谢谢
    猜你喜欢
    • 1970-01-01
    • 2018-10-02
    • 2019-06-23
    • 1970-01-01
    • 1970-01-01
    • 2020-02-09
    • 2017-06-14
    • 1970-01-01
    • 2020-06-08
    相关资源
    最近更新 更多