zoukankan      html  css  js  c++  java
  • 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>
    
  • 相关阅读:
    “”开天眼“”,天地分割效果
    关于获得当前的index的方法
    echart(2),模拟数据导入篇
    腾讯windows系统服务器
    elsarticle模板 去掉Preprint submitted to
    elsarticle模板 去掉摘要前后的两条横线
    LeetCode 345. Reverse Vowels of a String
    path变量修改后无法保存
    LeetCode 13: Roman to Integer
    LeetCode 118. Pascal's Triangle
  • 原文地址:https://www.cnblogs.com/guangzan/p/11838402.html
Copyright © 2011-2022 走看看