vue之 ref获取dom引用(替换掉jQuery)

本组件内获取标签的dom

获取子组件的dom

复制代码
<template>
  <div class="app-container">
    <h1 ref="myh12">App 根组件</h1>
    <button @click="showThis">打印 this</button>
    <button @click="onReset">重置 Left 组件的 count 值为 0</button>
    <hr />

    <input type="text" v-if="inputVisible" @blur="showButton" ref="iptRef" />
    <button v-else @click="showInput">展示输入框</button>

    <hr />

    <div class="box">
      <!-- 渲染 Left 组件和 Right 组件 -->
      <Left ref="comLeft"></Left>设置ref
    </div>
  </div>
</template>

<script>
import Left from '@/components/Left.vue'

export default {
  data() {
    return {
      // 控制输入框和按钮的按需切换;
      // 默认值为 false,表示默认展示按钮,隐藏输入框
      inputVisible: false
    }
  },
  /* updated() {
    this.$refs.iptRef.focus()
  }, */
  methods: {
    // 点击按钮,展示输入框
    showInput() {
      // 1. 切换布尔值,把文本框展示出来
      this.inputVisible = true
      // 2. 让展示出来的文本框,自动获取焦点
                  组件的 $nextTick(cb) 方法,会把 cb 回调推迟到下一个 DOM 更新周期之后执行。通俗的理解是:等组件的
                   DOM 更新完成之后,再执行 cb 回调函数。从而能保证 cb 回调函数可以操作到最新的 DOM 元素

this.$nextTick(() => { this.$refs.iptRef.focus() }) }, showButton() { this.inputVisible = false }, showThis() { // this 是当前 App 组件的实例对象 console.log(this) this.$refs.myh12.style.color = 'red' }, // 点击按钮,重置 Left 组件的 count 值 onReset() { this.$refs.comLeft.resetCount()执行子组件内的函数 // this.$refs.comLeft.count = 0 } }, components: { Left } } </script> <style lang="less"> .app-container { padding: 1px 20px 20px; background-color: #efefef; } .box { display: flex; } </style>
复制代码

 

posted @   强仔必胜  阅读(224)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示