Vue 3.0 -4 標籤參考ref
摘要
標籤參考ref用來
- id=title2相同名稱衝突
- 
解決母子組件當有相同名稱衝突時,宣告ref只有自己的頁面才可以訪問 
- 
組件使用ref時,必須組件定義defineExport({})才可以讓上層的組件可以訪問 
App.vue
<template>
  <div class="app">
   <div ref="title2">您好</div>
   <button @click="showLog">顯示id=title的值</button>
   <button @click="showSubRef">顯示組件的ref值</button>
   <main-watch-tag-ref ref="subRef"></main-watch-tag-ref>
  </div>
</template>
<script lang="ts" setup name="App">
  import MainWatchTagRef  from '@/components/MainWatchTagRef.vue';
  import { ref } from 'vue'
  //建立title2用於儲存ref的標籤內容
  let title2 = ref();
  //抓取組件的ref值
  let subRef = ref();
 
  //只會抓到自己的title2為"您好"
  function showLog(){
    console.log(title2.value)
  }
  //可以訪問到組件的car對象
  function showSubRef(){
    console.log(subRef.value)
    console.log(subRef.value.car)
  }
</script>
<style>
  .app {
    background-color:lightgray ;
    box-shadow: 0 0 10px;
    border-radius: 10px;
    padding: 20px;
    color: black;
  }
</style>
componets\MainWatchTagRef.vue
<template>
    <div class="person">
      <h2>Watch 範例.標簽的ref屬性</h2>
      <div ref="title2">我是Person</div>
      <div >我是Person</div>
      <button @click="showLog">顯示id=title的值</button>
    </div>
</template>
<script lang="ts" setup name="MainWatchEffect" >
  import {  ref,defineExpose} from 'vue'
  //建立title2用於儲存ref的標籤內容
  let title2 = ref();
  let car = {name:"benz",price:100000}
  defineExpose({car,title2})
  function showLog(){
    console.log(title2.value)
  }
</script>
<style scoped>
  .person {
    background-color:lightseagreen ;
    box-shadow: 0 0 10px;
    border-radius: 10px;
    padding: 20px;
    color: black;
  }
</style>



留言
張貼留言