先来回顾下 Vue2里面如何使用 调用ref 属性 :: 通过 this . $ref 调用 。
但setup函数无法获取 this 。
所以 ,在setup函数里面 定义一个const headline = ref(null),再return headline, 最后再把 headline 放在 模板的ref属性里 ref = “headline" 。
const headline = ref(null)
做完这两步之后,就可以直接在setup函数里 headline.value 调用 , = 之前的 this . $headline.
值得注意的是,ref拿到的是 整个标签元素 或 整个组件元素
<script>
import {
onMounted,
ref,
} from 'vue';
export default {
setup() {
const headline = ref(null);
// Before the component is mounted, the value
// of the ref is `null` which is the default
// value we've specified above.
onMounted(() => {
// Logs: `Headline`
console.log(headline.value.textContent);
});
return {
// It is important to return the ref,
// otherwise it won't work.
headline,
};
},
};
</script>
<template>
<div>
<h1 ref="headline">
Headline
</h1>
<p>Lorem ipsum ...</p>
</div>
</template>
总结 定义 const a = ref(xxx) return a 在 标签里 ref = ”a“ 即可绑定成功
使用直接 a.value
参考: https://markus.oberlehner.net/blog/refs-and-the-vue-3-composition-api/