vue.js - 如何在 Vue.js 的代码中更改组件属性的值?
问题描述
我的父组件中有一组通用子组件:
<component v-for="item in items" :key="item.id" :is="componentName">
我可以通过 得到一个孩子this.$refs
,但我不能为以下道具设置新值:is
:
this.$refs[id][0].is = 'MyNewComponentName'
如何在代码中设置组件实例属性的值?
解决方案
首先定义你的道具结构,如
{
...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 问题。
推荐阅读
- python - 根据字典中的“依赖项”对python列表进行排序
- excel - 在同一列的值的 6' 半径内查找并提取列中的值
- java - Spring Boot 以 Number 为键加载嵌套属性
- python - 与 Keras 的内置生成器相比,自定义 Keras 生成器要慢得多
- c# - 问题正确删除 WPF 中的属性绑定
- amazon-web-services - Terraform 错误:变量没有属性“private_ip”
- node.js - 回调错误不显示错误信息
- ios - 带有 CIFilters 的 AVVideoComposition 崩溃
- raspberry-pi - 如何在 Raspberry PI 上将 libusb-Win32 主机驱动程序安装到 Windows IoT
- php - 使用 PHP 加载信息时如何使用 PhpSpreadsheet 显示 Excel