ref 在 setup()函数里面的使用

先来回顾下 Vue2里面如何使用 调用ref 属性 :: 通过 this . $ref 调用 。 

但setup函数无法获取 this 。

所以  ,在setup函数里面 定义一个const headline = ref(null),再return headline, 最后再把 headline 放在 模板的ref属性里 ref = “headline" 。    

const headline = ref(null)

做完这两步之后,就可以直接在setup函数里 headline.value 调用 , =  之前的 this . $headline.

值得注意的是,ref拿到的是 整个标签元素 或 整个组件元素

<script>
import {
  onMounted,
  ref,
} from 'vue';

export default {
  setup() {
    const headline = ref(null);

    // Before the component is mounted, the value
    // of the ref is `null` which is the default
    // value we've specified above.
    onMounted(() => {
      // Logs: `Headline`
      console.log(headline.value.textContent);
    });

    return {
      // It is important to return the ref,
      // otherwise it won't work.
      headline,
    };
  },
};
</script>

<template>
  <div>
    <h1 ref="headline">
      Headline
    </h1>
    <p>Lorem ipsum ...</p>
  </div>
</template>

总结  定义 const a = ref(xxx)  return a     在 标签里 ref = ”a“  即可绑定成功  

使用直接 a.value

参考: https://markus.oberlehner.net/blog/refs-and-the-vue-3-composition-api/

https://www.jianshu.com/p/623c8b009a85

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值