vue.js - 如何修改子Vue组件中的值
问题描述
我正试图围绕 Vueprops
和data
属性的语义展开思考。在下面的代码中,子组件从父item
组件接受。newItem
子组件定义item
(抱歉含糊不清)为this.newItem
. parent 传入newItem
而不是item
为了绕过直接修改父组件值的禁止。
控制台没有显示任何警告,但我想知道是否只是因为 Vue 渲染(?)机器无法识别违规行为。item
在开发工具中可以看到child只是简单地创建对传入的引用newItem
,因此本质上 prop 仍然被直接修改。
我应该item
使用Item
构造函数来初始化孩子吗?或者孩子必须改为发出某种由父母处理的“取消编辑”事件?
cancelEdit
分配_cachedItem
给item
,与分配给 相同(?)newItem
:
// An item
Vue.component('item', {
props: [
'newItem'
],
data: function() {
return {
item: this.newItem,
editing: false,
_cachedItem: null
}
},
methods: {
startEdit: function() {
debugger
this._cachedItem = new Item(this.item.id, this.item.text);
this.editing = true;
},
cancelEdit: function() {
debugger
this.item = this._cachedItem;
this._cachedItem = null;
this.editing = false;
},
finishEdit: function() {
debugger
this.editing = false;
},
},
...
父模板:
Vue.component('items', {
props: {
'items': {
type: Array,
},
'item-type': {
type: String
}
...
<item
v-for="(item, index) in items"
v-bind:newItem="item"
v-bind:key="item.id"
v-on:remove="removeItem(index)" />
...