Vue中ref与$refs的使用

1.DOM元素上使用

<template>
    <div class="edit-input" :class="{'edit-input-show': is_edit}">
         <input type="text" v-model="info.content" ref="content" @keyup.enter="editData">
         <button @click="editData">确定</button>
     </div>

    <button @click="showInput(index)">编辑</button>
</template>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
methods:{
    showInput(index) {
        this.$refs.content.focus();
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5

2.子组件上使用

尽管有 prop 和事件,但是有时仍然需要在 JavaScript 中直接访问子组件。为此可以使用 ref 为子组件指定一个引用 ID。

<div id="parent">
    <user-profile ref="profile"></user-profile>
</div>
  • 1
  • 2
  • 3
var parent = new Vue({ el: '#parent' })
// 访问子组件实例
var child = parent.$refs.profile
  • 1
  • 2
  • 3

当 v-for 用于元素或组件的时候,引用信息将是包含 DOM 节点或组件实例的数组。

关于 ref 注册时间的重要说明:因为 ref 本身是作为渲染结果被创建的,在初始渲染的时候你不能访问它们 - 它们还不存在!

$refs 只在组件渲染完成后才填充,并且它是非响应式的。它仅仅是一个直接操作子组件的应急方案——应当避免在模板或计算属性中使用 $refs


猜你喜欢

转载自blog.csdn.net/qq_38698753/article/details/80605345