组合式vue使用$refs
时间: 2023-12-31 15:04:21 浏览: 82
在Vue 3中,由于使用了组合式API,所以无法像Vue 2中那样使用this.$refs来访问组件的属性或方法。取而代之的是使用getCurrentInstance方法来获取当前实例,并通过该实例的$refs属性来访问组件的ref属性。例如,在template标签中使用ref属性绑定一个组件:
```
<template>
<div>
<div>
<van-swipe class="my-swipe" ref="swipe" width="100%">
<van-swipe-item @click="toExhibitionPages">
<div>
<img src="./imgs/1.jpg" />
</div>
</van-swipe-item>
</van-swipe>
</div>
<div @click="nextImg">
<van-icon name="arrow" />
</div>
<div @click="preImg">
<van-icon name="arrow-left" />
</div>
</div>
</template>
<script setup>
import { ref, getCurrentInstance } from "vue";
const { proxy } = getCurrentInstance();
function nextImg() {
proxy.$refs.swipe.next();
}
function preImg() {
proxy.$refs.swipe.prev();
}
</script>
```
在这个例子中,我们通过getCurrentInstance方法获取到当前实例的proxy属性,并使用$refs属性来访问ref属性为"swipe"的组件。例如,我们可以通过proxy.$refs.swipe调用该组件的next和prev方法来切换图片。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* [在vue3组合式api中使用vue2的$refs](https://blog.csdn.net/weixin_55869175/article/details/124827021)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *2* [vue3使用$refs](https://blog.csdn.net/weixin_52164116/article/details/129683079)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
- *3* [计算机程序设计语言课程设计(VUE.js)及实践项目的例子.txt](https://download.csdn.net/download/weixin_44609920/88236928)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 33.333333333333336%"]
[ .reference_list ]
阅读全文