vue.js - 访问动态子组件
问题描述
如何访问我的子组件?例如,我的父组件具有以下“动态”组件(该组件在运行时一直在更改)。
<template>
<!-- The below component count be Component1 or Component2, etc. -->
<component id="my-cmp" v-if="templateComponent" :is="templateComponent"></component>
</template>
我怎样才能访问myCmp
调用函数...this.myCmp.doSomething()
不起作用。请注意,在此处使用 emit 不是解决方案,因为 emit 将调用doSomething()
所有“动态”组件,而不仅仅是当前组件。
下面是我的用法示例:
<template>
<!-- The below component count be Component1 or Component2, etc. -->
<component id="my-cmp" v-if="templateComponent" :is="templateComponent"></component>
</template>
<script type="text/javascript">
export default {
components: {
'cmp1': Component1,
'cmp2': Component1,
},
computed: {
templateComponent() {
// ...some logic that will determine if to use/chage to Component1 or Component2
return 'cmp1'
},
},
methods: {
someTrigger() {
// how can I reference #my-cmp?
// For the purpose of; myCmp.doSomething()
// I have tried the below technique BUT this will call doSomething
// on BOTH components not just the current/visible one
this.$emit('doSomethingNow') // Component1 and Component2 register using this.$parent.$on('doSomethingNow', this.doSomething)
}
}
}
</script>
解决方案
使用 ref 属性,举个例子:
Vue.component('com1',{
template: '<div>component com1</div>',
methods: {
fn () {
alert('method called')
}
}
})
var app = new Vue({
el: '#app',
data () {
},
computed: {
whichCom () {
return 'com1'
}
},
methods: {
btnClick () {
this.$refs.myCom.fn()
}
}
})
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<div id="app">
<component ref="myCom" v-if="whichCom" :is="whichCom"></component>
<button @click="btnClick">call method of com1</button>
</div>
推荐阅读
- generics - 在 Kotlin 中的 when 子句中组合多个 is
- c++ - Eigen3:如何在性能关键操作中访问矩阵系数?
- ansible - Ansible:如何以没有外壳的用户身份运行命令
- ios - 即使在 contentoffset(0,0) 之后,iOS tableView 也会向上滚动
- python-3.x - pypy3 导入 psycopg2 错误(未定义符号:PyCoder_Encoder)
- javascript - 使用 JavaScript 自动计费
- c++ - 链接静态库与共享库问题
- python - 有没有办法在 python 中对小端字节整数进行基本数学运算?
- java - Spring 的 WebClient 使用 MockServer 挂在 bodyToMono(Pojo) 上
- python - 使用指定用于颜色条的列的函数绘制 Excel 数据