Vue2 ref 引用

Vue 提供获取 DOM 元素的方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<template>
<div class="home">
<h1 ref="title"></h1>
<button @click="changeColor"></button>
</div>
</template>

<script>
export default {
data() {
return {}
},
methods: {
changeColor(){
this.$refs.title.style.color = 'red';
}
},
};
</script>

在元素上设置 ref 属性,可以在实例中通过 $refs 节点获取设置 ref 属性的 DOM 元素

如果是在组件标签上设置 ref 属性,则在 $refs 节点中获取的是这个组件实例