我注意到要在 Vue 3 组合 api 中制作模板引用 <script setup>
,我应该创建一个与 ref 值完全相同的变量名。
例如 Vue 3 documentation :
<template>
<div ref="root">This is a root element</div> <--- notice the ref name "root"
</template>
<script>
import { ref, onMounted } from 'vue'
export default {
setup() {
const root = ref(null) <---- and the variable name should be "root" too
onMounted(() => {
console.log(root.value)
})
return {
root
}
}
}
</script>
我想知道我是否可以像 Vue 2 那样使用 ref,因为我有一些元素,其 ref 是随机字符串,它在 Vue 2 上工作,只需在 $refs
上传递名称即可对象。
<div ref="myCustomRefName"></div>
<script>
let myRef = this.$refs["myCustomRefName"]
</script>
但我不能那样做,因为在 Vue3 中,我应该使变量名和 ref prop 值相似。任何帮助将不胜感激。
最佳答案
对我有用的是以下内容
<template>
<div ref="root">This is a root element</div> <--- notice the ref name "root"
<div ref="foo">this is foo element</div>
<div ref="bar">this is bar element</div>
</template>
<script>
import { ref, onMounted } from 'vue'
export default {
setup() {
const refs = {
root = ref(null), //<---- and the variable name should be "root" too
foo = ref(null),
bar = ref(null)
}
onMounted(() => {
console.log(root.value)
console.log(refs["root"])
})
return {
...refs
}
}
}
</script>
只需创建一个对象 refs(我将其称为 refs 只是因为怀旧)并使用您拥有的任何动态名称进行调用。
关于vue.js - Vue 3 模板引用动态名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68789245/