给标签增加ref属性,可以通过属性值取到标签内容
<template>
<div class="person">
<h1>this</h1>
<h2 ref="title">that</h2>
<button @click="showLog">changeTemp</button>
</div>
</template>
<script lang="ts" setup name="Person">
import {ref,watch,watchEffect} from 'vue'
let title = ref()
function showLog(){
console.log(title.value);
}
</script>
<style scoped>
.person {
background-color: skyblue;
box-shadow: 0 0 10px;
border-radius: 10px;
padding: 20px;
}
button {
margin : 0 5px;
}
li {
font-size : 20px;
}
</style>
data-v-xxxx 局部标识
如果在style中加了scoped,代表为局部样式,使用ref标签时会出现data-v-xxxx 标识
<style scoped>
</style>
在组件标签中使用ref标签
如果根组件想要获取components文件内的数据,需要两步:
- 在根组件内的组件标签内增加ref标签
- 对应组件文档中使用defineExpose
App.vue
<template>
<Person ref="temp"/>
<button @click="showLog">test</button>
</template>
<script lang="ts" setup name="App">
import Person from './components/Person.vue';
import {ref} from 'vue'
let temp = ref()
// 如果components的文件内不使用defineExpose,是无法获取到组件标签内的数据的
function showLog(){
console.log(temp.value);
}
</script>
Person.vue
<template>
<div class="person">
<h1>this</h1>
<h2 ref="title">that</h2>
<button @click="showLog">changeTemp</button>
</div>
</template>
<script lang="ts" setup name="Person">
import {ref,defineExpose} from 'vue'
let title = ref()
let a = ref(0)
let b = ref(1)
let c = ref(2)
function showLog(){
console.log(title.value);
}
// 将数据a,b暴露给根组件,隐藏c
defineExpose({a,b})
</script>
<style scoped>
.person {
background-color: skyblue;
box-shadow: 0 0 10px;
border-radius: 10px;
padding: 20px;
}
button {
margin : 0 5px;
}
li {
font-size : 20px;
}
</style>
标签:vue,title,标签,007,组件,let,ref
From: https://www.cnblogs.com/ayubene/p/18057400