vue3 ref标签标记dom

88 阅读1分钟

在vue3中ref函数通常用于进行基础类型数据的响应式绑定,除了这个功能,ref还可以在dom中作标记,用于解决不同组件中的dom冲突。 代码:

<template>
  <div  class="nihao">
    <h1 ref="title"></h1>
    <button @click="getTitle">获取h1</button>
  </div>
</template>

<script setup>

  import { ref} from 'vue'
  let title = ref()

  function getTitle(){
    console.log(title.value)
  }

</script>

<style scoped>
.nihao{
    background-color: bisque;
    height: auto;
}
</style>

说明:

  1. scirpt中导入ref模块
  2. 在dom元素中进行标记:<h1 ref="title"></h1>
  3. 在script中进行变量声明:let title = ref()
  4. 在函数中调用:function getTitle(){console.log(title.value)}
  5. 特别强调:dom中ref属性名称必须和let中定义的变量名一致,否则不能传递