Vue3| ref 模板引用、defineExpose宏函数

模板引用的概念:通过 ref 标识 获取真实的 dom对象或者组件实例对象

 

使用:

1. 调用 ref 函数生成一个 ref 对象

<script  setup>

import  { ref }  from  'vue'

const  h1Ref = ref (null)

</script>

2. 通过 ref 标识绑定 ref 对象到标签

<script  setup>

import  { ref }  from  'vue'

const  h1Ref = ref (null)

onMounted ( () => {

      console.log (h1Ref.value)

})

</script>

 

<template>

   <h1   ref = " h1Ref ">我是dom标签</h1>    // 可以通过 h1Ref.value 拿到绑定的 dom 对象(渲染完之后才能访问,所以<script>在里 用 onMounted 访问)

</template>

 

------------------------------------------------------------------------------------------------------------------------------------------

 

defineExpose ():

默认情况下在 <script  setup> 语法糖下 组件内部的属性和方法是不开放给父组件访问的,可以通过 defineExpose 编译宏 指定哪些属性和方法允许访问

<script  setup>

import  {ref}  from  'vue'

const  message = ref ('黑马程序员')

defineExpose ({

      message

})

</script>

 

posted @ 2023-10-14 11:04  1stzz1  阅读(324)  评论(0)    收藏  举报