vue3 template refs dom的引用、组件的引用、获取子组件的值

介绍

经过 ref() 还能够引用页面上的元素或组件。vue

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.vueapi

<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.vuedom

<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>
相关文章
相关标签/搜索