首页 > 解决方案 > 如何在 Vue.js 的代码中更改组件属性的值?

问题描述

我的父组件中有一组通用子组件:

<component v-for="item in items" :key="item.id" :is="componentName">

我可以通过 得到一个孩子this.$refs,但我不能为以下道具设置新值:is

this.$refs[id][0].is = 'MyNewComponentName'

如何在代码中设置组件实例属性的值?

标签: vue.jsvuejs2vue-component

解决方案


首先定义你的道具结构,如

{
  ...item, // to use your current variables
  componentName: 'MyExistingComponentName'
}

接收道具并将其绑定到数据变量,因此类似于

data: function() {
  returns {
     items: this.propItem
  }
}

在您的标签中进行必要的调整

<component v-for="item in items" :key="item.id" :is="item.componentName">

现在您有 2 个选项,您可以通过在方法中item.componentName引用来更改this.items,找到索引并更改它,或者您可以使用自定义事件让父级更改道具的值,使用$.event(event-name“MyNewComponent”)。这两种方法都很好,这真的取决于你的要求。

请参阅https://vuejs.org/v2/guide/components-custom-events.html 您还可以阅读有关 mutating prop 值的 stackoverflow 问题。


推荐阅读