首页 > 解决方案 > 如何修改子Vue组件中的值

问题描述

我正试图围绕 Vuepropsdata属性的语义展开思考。在下面的代码中,子组件从父item组件接受。newItem子组件定义item(抱歉含糊不清)为this.newItem. parent 传入newItem而不是item为了绕过直接修改父组件值的禁止。

控制台没有显示任何警告,但我想知道是否只是因为 Vue 渲染(?)机器无法识别违规行为。item在开发工具中可以看到child只是简单地创建对传入的引用newItem,因此本质上 prop 仍然被直接修改。

我应该item使用Item构造函数来初始化孩子吗?或者孩子必须改为发出某种由父母处理的“取消编辑”事件?

cancelEdit分配_cachedItemitem,与分配给 相同(?)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)" />
    ...

标签: vue.jsvue-component

解决方案


在 JavaScript 中,对象是通过引用传递的。Vue 文档清楚地指出..

请注意,JavaScript 中的对象和数组是通过引用传递的,因此如果 prop 是数组或对象,则在子组件内改变对象或数组本身影响父状态。

如果您想避免这种行为,您可以创建对象的深层克隆。像这样的东西..

item: JSON.parse(JSON.stringify(this.newItem)),

这将创建一个完全独立的对象本地副本。如果您想让两个对象保持同步,那么您可以通过事件向父对象传达您改变值的意图,并让它更新它自己的对象副本。处理此问题的一种优雅方法是使用.sync 修饰符


推荐阅读