常见用法
<template><CustomWin ref="sectionRef" class="ref-section"></CustomWin ><button @click="xx">点击</button>
</template><script setup lang="ts">
import {ref} from 'vue'
import CustomWin from "./CustomWin.vue"
const sectionRef = ref<InstanceType<typeof CustomWin>>();function xx(){if(sectionRef.value){// sectionRef.value.xxx 调用}
}</script>
如果我们需要在代码里面动态绑定ref,如果处理?
其实ref属性可以是个函数,(el)=>{},这样想怎样存储ref就可以怎样存储
<template><div v-for="(item, i) in list" :ref="el => { divs[i] = el }">{{ item }}</div>
</template><script>
import {onBeforeUpdate,reactive,ref,
} from 'vue';export default {setup() {const list = reactive([1, 2, 3]);const divs = ref([]);// Make sure to reset the refs before each update.onBeforeUpdate(() => {divs.value = [];});return {list,divs,};},
};
</script>
注:el是就是vue实例,赋值后访问的时候无需xx.value