ref 引用

什么是 ref 引用

  1. ref 用来辅助开发者在不依赖于 jQuery 的情况下,获取 DOM 元素或组件的引用。
  2. 每个 vue 的组件实例上,都包含一个 $refs 对象,里面存储着对应的 DOM 元素或组件的引用。默认情况下,组件的 $refs 指向一个空对象。
使用 ref 引用 DOM 元素
<h3 ref="myh3">MYRef 组件</h3>
<button @click="getRef">获取 $refs 引用</button>

methods: {
    getRef(){
        console.log(this.$refs.myh3);
        // 操作DOM元素,把文本颜色渲染为 red
        this.$refs.myh3.style.color = "red"
    }
},
使用 ref 引用组件实例
<Left ref="LeftRef"></Left>
<button @click="getRef">获取 $refs 引用</button>

methods: {
    getRef(){
        console.log(this.$refs.LeftRef);
        // 引用到组件之后就可以调用组件上的 methods 方法 (以 add() 为例)
        this.$refs.LeftRef.add()
    }
},
this.$nextTick(cb) 方法

组件的 $nextTick(cb) 方法,会把 cb 回调推迟到下一个 DOM 更新周期之后执行。通俗的理解是:等组件的
DOM 更新完成之后,再执行 cb 回调函数。从而能保证 cb 回调函数可以操作到最新的 DOM 元素。

以输入框和按钮之间的切换为例
  1. app.vue 组件
<template>
  <div class="app-container">
    <h1 ref="reference">App 根组件</h1>
    <button @click="showthis">this</button>
    ------
    <button @click="getcount">重置</button>
    <hr />

    <input type="text" v-if="visible" @blur="distinct" ref="iptref">
    <button @click="action" v-else>转换</button>

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

<script>
import Left from "./components/Left.vue"
export default {
  components:{
    Left
  },
  data() {
    return {
      visible : false
    }
  },
  methods: {
    showthis(){
      this.$refs.reference.style.color = 'red'
    },
    getcount(){
      this.$refs.oncom.resetcount()
    },
   action(){
     this.visible = true

     this.$nextTick(()=>{
       this.$refs.iptref.focus()
     })
   },
   distinct(){
     this.visible = false
   }
  },
}
</script>

<style lang="less">
.app-container {
  padding: 1px 20px 20px;
  background-color: #efefef;
}
.box {
  display: flex;
}
</style>

当文本框展示出来之后立即获得焦点,为其添加 ref 引用,并调用原生 DOM 对象的 .focus() 方法

  1. Left.vue 组件
<template>
  <div class="left-container">
    <h3>Left 组件</h3>
    <p>count + 1 的结果为 : {{count}}</p>
    <button @click="add">+1</button>
    ---------
    <button @click="resetcount">重置</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      count : 0
    }
  },
  methods: {
    add(){
      this.count += 1
    },
    resetcount(){
      this.count = 0
    }
  },
}
</script>

<style lang="less">
.left-container {
  padding: 0 20px 20px;
  background-color: orange;
  min-height: 250px;
  flex: 1;
}
</style>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值