Vue3:标签属性ref

        在获取标签元素的方法中,通常的js方法如:document.getElementById这么长的API来获取。还有jQuery的:$(#id),在Vue2中我们还是用的方法是this.$refs。那么我们在Vue3中如何使用ref呢?

示例:

        获取div标签的内容

        

<template>

  <div>

    <div ref="labelDiv">123</div>

  </div>

</template>

<script lang="ts"  setup>

import { reactive, ref, getCurrentInstance, onMounted } from 'vue'

const labelDiv = ref()

onMounted(()=>{

  console.log('labelDiv',labelDiv.value.innerText)

})

</script>

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 3 中,`ref` 是一个新的响应式 API,用于在模板中引用一个元素或组件,并可以在 JavaScript 代码中访问该元素或组件的属性和方法。 在模板中,可以使用 `ref` 指令来创建一个 `ref` 对象,并将其绑定到一个元素或组件上。例如: ```html <template> <div> <input type="text" ref="inputRef" /> <button @click="handleClick">Click Me</button> </div> </template> <script> import { ref } from 'vue'; export default { setup() { const inputRef = ref(null); function handleClick() { inputRef.value.focus(); } return { inputRef, handleClick, }; }, }; </script> ``` 在这个例子中,我们使用 `ref` 指令将 `input` 元素绑定到 `inputRef` 变量上。在 `setup` 函数中,我们使用 `ref` 函数创建了一个 `ref` 对象,并将其初始值设置为 `null`。然后,我们在 `handleClick` 函数中访问了 `inputRef.value`,并调用了 `focus` 方法,以便将焦点设置到 `input` 元素上。 需要注意的是,在 Vue 3 中,`ref` 不再返回一个对象,而是返回一个包含 `value` 属性的普通 JavaScript 对象。因此,在访问 `ref` 对象的属性和方法时,需要使用 `.value` 来访问其值。 另外,在 Vue 3 中,`ref` 还可以用于引用组件,例如: ```html <template> <div> <MyComponent ref="myComponentRef" /> <button @click="handleClick">Click Me</button> </div> </template> <script> import { ref } from 'vue'; import MyComponent from './MyComponent.vue'; export default { components: { MyComponent, }, setup() { const myComponentRef = ref(null); function handleClick() { myComponentRef.value.someMethod(); } return { myComponentRef, handleClick, }; }, }; </script> ``` 在这个例子中,我们使用 `ref` 指令将 `MyComponent` 组件绑定到 `myComponentRef` 变量上。在 `setup` 函数中,我们使用 `ref` 函数创建了一个 `ref` 对象,并将其初始值设置为 `null`。然后,我们在 `handleClick` 函数中访问了 `myComponentRef.value`,并调用了 `someMethod` 方法,以便调用 `MyComponent` 组件的某个方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值