vue.js函数模板引用

发布时间 2023-10-07 13:48:11作者: 邢帅杰

// 参考网址:https://cn.vuejs.org/guide/essentials/template-refs.html#ref-on-component
// 模板引用也可以被用在一个子组件上。这种情况下引用中获得的值是组件实例:
// 如果一个子组件使用的是选项式 API 或没有使用 <script setup>,被引用的组件实例和该子组件的 this 完全一致,
// 这意味着父组件对子组件的每一个属性和方法都有完全的访问权。
// 这使得在父组件和子组件之间创建紧密耦合的实现细节变得很容易,当然也因此,应该只在绝对需要时才使用组件引用。
// 大多数情况下,你应该首先使用标准的 props 和 emit 接口来实现父子组件交互。
// 有一个例外的情况,使用了 <script setup> 的组件是默认私有的:一个父组件无法访问到一个使用了 <script setup> 的子组件中的任何东西,
// 除非子组件在其中通过 defineExpose 宏显式暴露。

<!-- 模板引用 -->
<template>
    <input id="txtName" ref="txtName" value="jay.star">
    <el-button type="primary" @click="ShowName()">click</el-button>
</template>
<script setup>
import {
  reactive,
  ref,
  getCurrentInstance,
  onMounted,
  computed,
  toRefs,
  watch,
  watchEffect,
  watchPostEffect,
  onUpdated,
  onUnmounted
} from "vue";
// 声明一个 ref 来存放该元素的引用
// 必须和模板里的 ref 同名
const txtName = ref(null);
// 模板引用,根据引用对象获取值。
function ShowName(){
    let ctlId = txtName.value.id;
    let name = document.getElementById(ctlId).value;
    alert(name);
}

// 只可以在组件挂载后才能访问模板引用
onMounted(() => {
    //txtName.value.focus()
});

// 如果你需要侦听一个模板引用 ref 的变化,确保考虑到其值为 null 的情况:
watchEffect(() => {
  if (txtName.value) {
    console.log("组件已挂载");
    txtName.value.focus();
  } else {
    console.log("此时还未挂载,或此元素已经被卸载(例如通过 v-if 控制)");
  }
})
</script>