Vue3 setup 怎么使用this.$refs
时间: 2024-03-15 10:38:25 浏览: 33
根据提供的引用内容,Vue3的setup中没有绑定this,因此无法使用this.$refs来获取节点。但是,我们可以使用以下两种方法来获取节点:
方法一:
```vue
<template>
<p ref="myRef">hello</p>
</template>
<script>
import { ref, onMounted } from 'vue'
export default {
setup() {
const myRef = ref(null)
onMounted(() => {
console.log(myRef.value) // 输出: <p>hello</p>
})
return {
myRef
}
}
}
</script>
```
方法二:
```vue
<template>
<p ref="myRef">hello</p>
</template>
<script setup>
import { onMounted, getCurrentInstance } from 'vue'
const p = getCurrentInstance()
const { proxy } = getCurrentInstance()
onMounted(() => {
console.log(p.refs.myRef) // 输出: <p>hello</p>
console.log(proxy.$refs.myRef) // 输出: <p>hello</p>
})
</script>
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)