前言
Vue中ref的使用:ref被用来给DOM元素或子组件注册引用信息。如果在普通的DOM元素上使用,引用信息就是元素;如果在子组件上使用,引用信息就是组件实例。
注意:在Vue中直接操作DOM元素,就必须用ref属性进行注册。
在Vue2中的用法
<template>
<div id="app">
<div ref="testDom">11111</div>
<button @click="getTest">获取test节点</button>
</div>
</template>
<script>
export default {
methods: {
getTest() {
console.log(this.$refs.testDom)
}
}
};
</script>
Vue3中的用法
<template>
<div id="app">
<div ref="testDom">11111</div>
<button @click="getTest">获取test节点</button>
</div>
</template>
<script>
import { ref } from "vue";
export default {
setup(Proxy) {
const testDom = ref('')
const getTest = () => {
console.log(testDom.value);
}
return {
getTest,
testDom
}
},
}
</script>