- 用在普通DOM标签上,获取的是DOM节点。
- 用在组件标签上,获取的是组件实例对象。
用在普通DOM标签中
获取dom元素方法一:
- 在需要获取的元素标签上添加ref属性
- 创建ref对象,存储ref属性标记的内容
- 通过ref上的value属性即可获取当前dom元素
| <template> |
| <p>{{ person.name }}</p> |
| <!--1.在标签上写上ref属性--> |
| <div ref="msg">{{ person.age }}</div> |
| <p>{{ person.gender }}</p> |
| <button @click="getEle">获取元素</button> |
| </template> |
| |
| <script setup> |
| import { ref, reactive, computed, getCurrentInstance, onMounted } from "vue"; |
| |
| const person = reactive({ |
| name: "neko", |
| age: 18, |
| gender: "女", |
| }); |
| |
| |
| let msg = ref(); |
| |
| |
| const getEle = () => { |
| console.log(msg.value); |
| }; |
| </script> |
复制
获取dom元素方法二:
getCurrentInstance():获取当前组件实例
- 在需要获取的元素标签上添加ref属性
- 通过getCurrentInstance解构出proxy
- 通过proxy.$refs.xxx即可获取当前dom元素
| <template> |
| <p>{{ person.name }}</p> |
| <!--1.在标签上写上ref属性--> |
| <div ref="msg">{{ person.age }}</div> |
| <p>{{ person.gender }}</p> |
| <button @click="getEle">获取元素</button> |
| </template> |
| |
| <script setup> |
| import { ref, reactive, computed, getCurrentInstance, onMounted } from "vue"; |
| |
| |
| const { proxy } = getCurrentInstance(); |
| |
| const person = reactive({ |
| name: "neko", |
| age: 18, |
| gender: "女", |
| }); |
| |
| |
| const getEle = () => { |
| console.log(proxy.$refs.msg); |
| }; |
| </script> |
复制
用在组件标签上
defineExpose作用:向外暴露属性
| <!-- 父组件 --> |
| <template> |
| <Demo ref="demoRef"></Demo> |
| </template> |
| |
| <script setup> |
| import { ref, onMounted } from "vue"; |
| import Demo from "./components/Demo.vue"; |
| |
| let demoRef = ref(); |
| |
| onMounted(() => { |
| console.log(demoRef.value); |
| }); |
| </script> |
| |
| |
| <!-- 子组件 --> |
| <template> |
| <p>{{ person.name }}</p> |
| <div>{{ person.age }}</div> |
| <p>{{ person.gender }}</p> |
| </template> |
| |
| <script setup> |
| import { ref, reactive, computed, getCurrentInstance, onMounted } from "vue"; |
| |
| const person = reactive({ |
| name: "neko", |
| age: 18, |
| gender: "女", |
| }); |
| |
| let num1 = ref(0); |
| let num2 = ref(1); |
| let num3 = ref(2); |
| |
| defineExpose({ num1, num2, num3, person }); |
| </script> |
复制