在 Vue3 中,怎么使用 $refs 访问元素引用的方法。Vue2 中相比有所不同,直接使用
this.$refs["refTable"]
给我一个实例,在 Vue3 中使用 refs 来访问elementui-plus的 组件的实例
<template>
<el-table
ref="multipleTableRef"
:data="tableData"
style="width: 100%"
@selection-change="handleSelectionChange"
>
<!-- 省略表格列的定义 -->
</el-table>
</template>
<script>
import { ref } from 'vue'
export default {
setup() {
const multipleTableRef = ref(null)
// 访问表格组件实例
function submit() {
const table = multipleTableRef.value
// do something with the table instance
}
return {
multipleTableRef,
submit
}
}
}
</script>
在Vue3中,使用$refs访问元素引用的方法与Vue2中略有不同
在Vue3中,需要在模板中使用 ref 属性来定义元素的引用,然后在组件实例中使用 ref 函数来访问这个引用。
如有一个 div 元素,可以在模板中定义它的引用:
<template>
<div ref="myDiv">Hello, world!</div>
</template>
然后在组件实例中,使用 ref 函数来访问这个引用:
import { ref, watchEffect } from 'vue'
export default {
setup() {
const myDiv = ref(null)
watchEffect(() => {
console.log(myDiv.value.textContent)
})
return {
myDiv
}
}
}
在这个例子中,使用 ref 函数来创建一个 myDiv 引用,并在 watchEffect 监听器中访问这个引用的内容。
需要注意的是,在Vue3中,ref 函数返回的是一个响应式对象,因此需要使用 myDiv.value 来访问这个引用
Vue3 中通过 ref 访问元素节点与 Vue2 不太一样,在 Vue3 中我们是没有 this 的,所以当然也没有 this.$refs。想要获取 ref,我们只能通过声明变量的方式。
创建一个 Vite 项目:
为了方便演示,我们直接在 Vite 项目中演示 ref 代码,创建项目指令如下:
npm create vite@latest my-vue-app --template vue-ts
代码如下:
<template>
<div ref="hello">小猪课堂</div>
</template>
<script setup lang="ts">
import { onMounted, ref } from "vue";
const hello = ref<any>(null);
onMounted(() => {
console.log(hello.value); // <div>小猪课堂</div>
});
</script>
上段代码中我们同样给 div 元素添加了 ref 属性,为了获取到这个元素,我们声明了一个与 ref 属性名称相同的变量 hello,然后我们通过 hello.value 的形式便获取到了该 div 元素。
注意点:
在 Vue3 中使用 $refs 访问组件引用的方法的步骤如下:
Click Me
import { ref, toRef } from 'vue'
setup() { const buttonRef = ref(null) const buttonEl = toRef(buttonRef, 'value.$el')
// 在 mounted 钩子中访问 $refs 方法 onMounted(() => { console.log(buttonRef.value) // 访问按钮的组件实例 console.log(buttonEl.value) // 访问按钮的 DOM 元素 })
return { buttonRef } }
import { ref, toRef, onMounted, onUpdated } from 'vue'
setup() { const buttonRef = ref(null) const buttonEl = toRef(buttonRef, 'value.$el')
// 访问 $refs 方法 onMounted(() => { console.log(buttonRef.value) // 访问按钮的组件实例 console.log(buttonEl.value) // 访问按钮的 DOM 元素 })
// 更新 $refs 方法 onUpdated(() => { console.log(buttonRef.value) // 访问更新后的组件实例 console.log(buttonEl.value) // 访问更新后的 DOM 元素 })
return { buttonRef } }