在vue2中,我可以使用这个。$el
export default {
render() {
return this.$slots.default[0]
},
mounted() {
Sortable.create(this.$el, {});
})
}如果在vue3中我尝试使用this.$slots.default(),我看不到如何定位元素。如果我使用模板ref,我可以得到div,但不能得到包含的槽。
我找到的最接近的问题/答案是here Vue 3 Composition API - How to get the component element ($el) on which component is mounted
但这似乎也给出了div,但没有给出插槽$el。
这在vue2中非常强大,因为sortable可以在一个插槽中传递一个ul,或者一个div,或者另一个构造的可排序的vue组件,并且不需要在子组件中定义元素就可以工作,我不知道如何在vue3中复制它。
我最初是在Adam Wathan的屏幕上看到这一点的:“用Vue.js构建一个可排序的组件”,但这是vue2。
发布于 2021-09-05 14:38:11
我想出了以下几点(也许还有更好的)
使用模板引用:
<template>
<div ref="root">
<slot></slot>
</div>
</template>然后在脚本中:
import { ref, onMounted } from 'vue'
export default {
setup() {
const root = ref(null)
onMounted(() => {
// the DOM element will be assigned to the ref after initial render
// console.log(root.value.children[0]) // this is your $el
let el = root.value.children[0]
Sortable.create(el, {})
})
return {
root
}
}
}https://stackoverflow.com/questions/69062558
复制相似问题