简体   繁体   English

将 v-model 与数组一起使用时,从 vue.js 获取无法读取未定义错误的属性

[英]getting a cannot read property of undefined error from vue.js when using v-model with an array

I'm trying to v-model to an array item's property.我正在尝试对数组项的属性进行v-model When I load the page I see "[Vue warn]: Error in render function: 'TypeError: Cannot read property 'viewFood' of undefined' in the console and a blank page.当我加载页面时,我在控制台中看到"[Vue warn]: Error in render function: 'TypeError: Cannot read property 'viewFood' of undefined'和一个空白页面。

this is with vue.js 2.x.这是 vue.js 2.x。

https://codepen.io/jzaun/pen/YxYyJN/ https://codepen.io/jzaun/pen/YxYyJN/

html html

<div id="ai-config">
  <div class="info">
    <div class="row">
      <h1>Resource Points</h1>
    </div>
    <div class="row">
      <label>Total:</label>
      <div class="value">
        {{maxResourcePoints}}
      </div>
    </div>
    <div class="row">
      <label>Remaining:</label>
      <div class="value">
        {{maxResourcePoints - usedResourcePoints}}
      </div>
    </div>
  </div>
  <div>
    <table>
      <tr>
        <td></td>
        <td v-for="(option, idx) in options">
          {{option.title}}
        </td>
      </tr>
      <tr v-for="n in directions">
        <td>Direction {{n}}</td>
        <td v-for="option in options">
          <input type="checkbox", v-model="selected[n][option.key]" />
        </td>
      </tr>
    </table>
  </div>
</div>

javascript javascript

new Vue ({
  el: '#ai-config',

  data: {
    maxResourcePoints: 10,
    usedResourcePoints: 0,
    selected: [],

    directions: 8,
    options: [{
      title: 'Food',
      key: 'viewFood',
      cost: 1
    }, {
      title: 'Water',
      key: 'viewWater',
      cost: 1
    }, {
      title: 'Own',
      key: 'viewOwn',
      cost: 1
    }, {
      title: 'Other',
      key: 'viewOther',
      cost: 1
    }]
  },

  methods: {
  },

  created: function () {
    this.selected = [];
    for(i=0; i< 8; i++) {
      this.selected.push({});
    }
  }
});

There are two primary issues.有两个主要问题。

First, Vue cannot detect when you add a property dynamically to an object that has been added to the Vue's data.首先,当您将属性动态添加到已添加到 Vue 数据中的对象时, Vue 无法检测到。 When you do this:当你这样做时:

v-model="selected[n][option.key]"

You are adding a property to the empty object you initialized in the create handler.您正在向您在create处理程序中初始化的空对象添加一个属性。 To fix that, just initialize with actual properties (or use $set , which doesn't appear to be an option here).要解决这个问题,只需使用实际属性进行初始化(或使用$set ,这里似乎不是一个选项)。

this.selected.push({viewFood: false, viewOwn: false, viewWater: false, viewOther: false});

Second (and the cause of the error you quote in your question), when you use a range v-for the values start at 1. So其次(以及您在问题中引用的错误的原因),当您使用范围v-for值从 1 开始时。所以

v-model="selected[n][option.key]"

has an off by one error because as you likely know, Javascript arrays are zero based.有一个错误,因为您可能知道,Javascript 数组是从零开始的。 It should be它应该是

v-model="selected[n - 1][option.key]"

There was also a minor HTML error in the original pen原始笔中还有一个小的 HTML 错误

<input type="checkbox", v-model="selected[n][option.key]" />

where the comma should be removed.应删除逗号的位置。

Here is your pen updated .这是你的笔更新

I think that I have the code you need.我想我有你需要的代码。 Check it out here https://codepen.io/spaquet/pen/MvrbLQ在这里查看https://codepen.io/spaquet/pen/MvrbLQ

I made the following change:我做了以下更改:

  1. Adding value and id to all checkboxes and making sure that they are all different so you can identify which one is clicked.为所有复选框添加 value 和 id 并确保它们都是不同的,以便您可以识别单击了哪个复选框。
  2. Removed your created function.删除了您创建的功能。 Useless as selected is defined in data (my opinion is that you may want to keep the state between relead...)数据中定义了选定的无用(我的观点是您可能希望保持重新引导之间的状态......)
  3. Added a click function to all the checkboxes.为所有复选框添加了click功能。 It is used to visualize the state of the selected at every iteration.它用于在每次迭代中可视化选定对象的状态。

You can now have in selected the list of the elements that are selected with the following format direction-option.key (1-viewFood, etc.)您现在可以选择具有以下格式的元素列表 direction-option.key (1-viewFood 等)

<tr v-for="n in directions">方向应该是数组而不是数字

You initialize selected to contain a bunch of {} objects.您初始化 selected 以包含一堆 {} 对象。 selected[n] will be an empty object, so naturally selected[n][option.key] is null. selected[n]将是一个空对象,所以很自然selected[n][option.key]为空。

Changing <input type="checkbox", v-model="selected[n][option.key]" /> to <input type="checkbox" v-model="option.key"> works to me - it renders.<input type="checkbox", v-model="selected[n][option.key]" />更改为<input type="checkbox" v-model="option.key">对我有用 - 它呈现. All the checkboxes in a column point to the same value though - this is probably not what you want.但是,列中的所有复选框都指向相同的值 - 这可能不是您想要的。 This is because they all reference the same v-model这是因为它们都引用了相同的v-model

Can you explain a little more about what this is supposed to do?你能解释一下这应该做什么吗? I can help you fix it then.那我可以帮你修。 Vue is great framework once you understand how it works.一旦你了解了它的工作原理,Vue 就是一个很棒的框架。 Maybe a mockup of what this should do or a little more explanation.也许这是应该做什么的模型或更多解释。 Thanks.谢谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM