好吧。我其实不太理解模板引用的概念以及的实际应用场景是什么。如果有知道的大佬麻烦详细讲解下
一、基础应用
使用下述代码替换app.vue
中代码
<script setup>
import { ref, onMounted } from 'vue'
// 声明一个 ref 来存放该元素的引用
const elementData = ref(null)
function getElementData(){
console.error(elementData.value)
}
</script>
<template>
<!--使用ref-->
<h3 ref="elementData">测试一下</h3>
<button @click="getElementData">获取数据</button>
</template>
二、v-for中的模板引用
在v-for
中使用模板引用,对应的ref
中包含的是一个数组(不保证跟源数组相同顺序)
<script setup>
import { ref, onMounted } from 'vue'
const names = ref(['张三', '李四'])
// 声明一个 ref 来存放该元素的引用
const elementData = ref([])
function getElementData(){
console.error(elementData.value)
}
</script>
<template>
<ul>
<li v-for="name in names" ref="elementData">{{name}}</li>
</ul>
<button @click="getElementData">获取数据</button>
</template>