ref $refs(元素、组件引用 )
ref $refs(元素、组件引用 )
ref 属性
给组件 ref,得到的是组件的实例对象
ref 被用来给元素或子组件注册引用信息( id 的替代者),引用信息将会注册在父组件的
$refs
对象上。随后可以进行一些 DOM 操作或者其他操作。使用方式:
- 标识:
<h1 ref="xxx"></h1>
或<School ref="xxx"></School>
- 获取:
this.$refs.xxx
<!-- `vm.$refs.p` will be the DOM node --> <p ref="p">hello</p> <!-- `vm.$refs.child` will be the child component instance --> <child-component ref="child"></child-component>
1
2
3
4
5- 标识:
如果在普通的 DOM 元素上使用,引用指向的就是 DOM 元素;
如果用在子组件上,引用就指向组件实例对象(VueComponent):
关于 ref 注册时间的重要说明:因为 ref 本身是作为渲染结果被创建的,在初始渲染的时候不能访问它们 - 它们还不存在!$refs
也不是响应式的,因此不应该试图用它在模板中做数据绑定。
DOM 引用
<div id="app">
<input type="text" ref="input1" id="input1" />
<button @click="add">添加</button>
</div>
<script src="../js/vue.js"></script>
<script type="text/javascript">
var vm = new Vue({
el: '#app',
methods: {
add: function () {
this.$refs.input.value = 22 // 获取节点的消耗小于普通的方式
console.log(this.$refs.input1) // <input type="text" id="input1"/>
console.log(document.getElementById(input1)) // <input type="text" id="input1"/>
},
},
})
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
子组件引用
尽管存在 prop 和事件,有的时候仍需要在 JavaScript 里直接访问一个子组件。为了达到这个目的,你可以通过 ref
这个 attribute 为子组件赋予一个 ID 引用。<base-input ref="usernameInput"></base-input>
,之后可以通过this.$refs.usernameInput
来访问这个子组件
<div id="app">
<input type="text" ref="input1" id="input1" />
<button @click="add">添加</button>
<my-component ref="com"></my-component>
</div>
<script src="../js/vue.js"></script>
<script type="text/javascript">
Vue.component('my-component', {
template: '<div>我是一个组件</div>',
})
var vm = new Vue({
el: '#app',
methods: {
add: function () {
this.$refs.input.value = 22 // 获取节点的消耗小于普通的方式
console.log(this.$refs.input1) // <input type="text" id="input1"/>
console.log(document.getElementById(input1)) // <input type="text" id="input1"/>
},
},
})
</script>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
与v-for
结合
当 ref
和 v-for
一起使用的时候,得到的 ref 将会是一个包含了对应数据源的这些子组件的数组。
当 v-for
用于元素或组件的时候,引用信息将是包含 DOM 节点或组件实例的数组。
上次更新: 2025/02/26, 08:57:57