vue3 template refs dom的引用、組件的引用、獲取子組件的值


介紹

通過 ref() 還可以引用頁面上的元素或組件。

DOM 的引用

<template>
  <div>
    <h3 ref="h3Ref">TemplateRefOne</h3>
  </div>
</template>

<script>
import { ref, onMounted } from '@vue/composition-api'

export default {
  setup() {
    // 創建一個 DOM 引用
    const h3Ref = ref(null)

    // 在 DOM 首次加載完畢之后,才能獲取到元素的引用
    onMounted(() => {
      // 為 dom 元素設置字體顏色
      // h3Ref.value 是原生DOM對象
      h3Ref.value.style.color = 'red'
    })

    // 把創建的引用 return 出去
    return {
      h3Ref
    }
  }
}
</script>

組件的引用

父組件獲取子組件的值
父組件 templateRefOne.vue

<template>
  <div>
    <h3>TemplateRefOne</h3>

    <!-- 4. 點擊按鈕展示子組件的 count 值 -->
    <button @click="showNumber">獲取TemplateRefTwo中的count值</button>

    <hr />
    <!-- 3. 為組件添加 ref 引用 -->
    <TemplateRefTwo ref="comRef" />
  </div>
</template>

<script>
import { ref } from '@vue/composition-api'
import TemplateRefTwo from './TemplateRefTwo'

export default {
  setup() {
    // 1. 創建一個組件的 ref 引用
    const comRef = ref(null)

    // 5. 展示子組件中 count 的值
    const showNumber = () => {
      console.log(comRef.value.count)
    }

    // 2. 把創建的引用 return 出去
    return {
      comRef,
      showNumber
    }
  },
  components: {
    TemplateRefTwo
  }
}
</script>

子組件 templateRefTwo.vue

<template>
  <div>
    <h5>TemplateRefTwo --- {{count}}</h5>
    <!-- 3. 點擊按鈕,讓 count 值自增 +1 -->
    <button @click="count+=1">+1</button>
  </div>
</template>

<script>
import { ref } from '@vue/composition-api'

export default {
  setup() {
    // 1. 定義響應式的數據
    const count = ref(0)

    // 2. 把響應式數據 return 給 Template 使用
    return {
      count
    }
  }
}
</script>


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM