如果插槽的模板中有一些引用,我如何从组件访问这些引用?例如:
v-component.vue
<template>
<div>
<slot></slot>
</div>
</template>
<script>
export default {
created() {
console.log(this.$refs.ele)
}
}
</script>
应用程序
<template>
<v-component>
<template slot-scope="props">
<h1 ref="ele"></h1>
</template>
</v-component>
</template>
<script>
import VComponent from './v-component
export default {
components: { VComponent }
}
</script>
v-component.vue 输出中的 this.$refs.ele 未定义。我的问题是我怎样才能得到这个元素?
最佳答案
命名 slot
中的每个元素和 scopedSlot
有 context.$refs
.
不要忘记先检查对象是否存在。
<template>
<v-component>
<template slot-scope="props">
<h1 ref="ele">{{ props }}</h1>
</template>
</v-component>
</template>
<script>
import VComponent from './v-component'
export default {
components: { VComponent }
}
</script>
和
<template>
<div>
<slot demo="foo"></slot>
</div>
</template>
<script>
export default {
created() {
this.$nextTick(function() { // lazy
console.warn(this.$scopedSlots.default()[0].context.$refs)
});
}
}
</script>
结果:
关于vue.js - 如何在作用域插槽中获取 refs 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52440368/