模板编译

59 阅读1分钟

ref的定义

声明一个同名的 ref, 必须是同名的

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

// 声明一个 ref 来存放该元素的引用
// 必须和模板里的 ref 同名
const input = ref(null)

onMounted(() => {
  input.value.focus()
})
</script>

<template>
  <input ref="input" />
</template>

v-for 中的模板引用

当在 v-for 中使用模板引用时,对应的 ref 中包含的值是一个数组; ref 数组并不保证与源数组相同的顺序

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

const list = ref([
  /* ... */
])

const itemRefs = ref([])

onMounted(() => console.log(itemRefs.value))
</script>

<template>
  <ul>
    <li v-for="item in list" ref="itemRefs">
      {{ item }}
    </li>
  </ul>
</template>

函数模板引用

ref attribute 还可以绑定为一个函数

<input :ref="(el) => { /* 将 el 赋值给一个数据属性或 ref 变量 */ }">

组件上的 ref

父组件获取子组件的实例 使用了 <script setup> 的组件是默认私有的, 父组件获取到了子组件的实例的情况下是拿不到任何子组件的东西的. 子组件可以通过defineExpose宏显示暴露出来

// 父组件
const myChild = ref(null)
onMounted(() => {
    console.log(myChild.value);
});

<template>
    child: <Child ref="myChild" />
</template>
// 子组件
<script setup>
import { ref, defineExpose } from 'vue';
const a = 1
const b = ref(2)
defineExpose({
    a,
    b
})
</script>

<template>
    <span>child component</span>
</template>