【问题标题】:Property mutation in VuejsVuejs 中的属性突变
【发布时间】:2017-06-28 10:05:30
【问题描述】:

所以我有多个这样的代码:

<input id="data" type="text"  v-model="data">
<label for="data">Data</label>

并且我试图用它来制作一个属性,这样我就不会每次都重复它:

Vue.component('textbox', {
  template: `
   <div>
   <input :id="id" type="text" v-model="value">
   <label :for="id">{{ label }}</label>
   </div>
  `,
  props: [
      "id", "value", "label", "for"],
  watch: {
    value: function(newVal){
       this.$emit('input', newVal)
    }
  }
})

并像这样在我的 html 中访问它:

<textbox v-model="data" id="someID" label="Data"></textbox>

一切正常,但每次我在文本框中输入时,我都会在控制台中收到以下警告:

[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "value" 
(found in component <textbox>)

有没有办法删除该警告消息?还是我做错了?任何帮助将不胜感激。

【问题讨论】:

  • 错误本身说 相反,使用基于道具值的数据或计算属性,所以代替道具尝试数据或计算道具
  • @VinodLouis 你介意给我举个例子吗?老实说,我不明白

标签: javascript html vue.js vuejs2 vue-component


【解决方案1】:

您根本不需要使用手表。而不是使用 v-model,试试这个:

<input :id="id" type="text" :value="value" @input="$emit('input', $event.target.value)">

工作示例:http://codepen.io/CodinCat/pen/dNQopR?editors=1010

【讨论】:

  • 做到了!谢谢。
猜你喜欢
  • 1970-01-01
  • 2020-07-01
  • 2014-06-12
  • 2017-08-23
  • 2018-08-13
  • 1970-01-01
  • 2018-11-18
  • 2019-02-11
  • 2021-09-21
相关资源
最近更新 更多