1、如果多个页面都用同一个id,那么就会报错。用ref可以指明是某个元素,规避报错情况。App.vue代码如下:
<template> <div class="app"> <h2 ref="title2">好好学习,天天向上</h2> <button @click="showLog">点我输出h2元素</button> <Person/> </div> </template> <script lang="ts" setup name="App"> // JS或TS import Person from './view/Person.vue' import {ref} from 'vue' let title2 = ref() function showLog() { console.log(title2.value) } </script> <!--样式 scoped表示仅本单元有效--> <style scoped> .app { background-color: #ddd; box-shadow: 0 0 10px; border-radius: 10px; padding: 20px; } </style>
2、person.vue代码如下:
<template> <div class="person"> <h1>中国</h1> <h2 ref="title2">北京</h2> <h3>海淀</h3> <button @click="showLog">点我输出h2元素</button> </div> </template> <script lang="ts" name="Person001" setup> import {ref} from 'vue' let title2 = ref() function showLog() { console.log(title2.value) } </script> <style scoped> .person { background-color: #ddd; box-shadow: 0 0 10px; border-radius: 10px; padding: 20px; button { margin: 0 5px; } } </style>
3、效果如下:
标签:TypeScript,011,title2,vue,报错,template,10px,import,ref From: https://www.cnblogs.com/tianpan2019/p/18364912