ref引用
ref用来辅助开发者在不依赖于jQery的情况下,获取DOM元素或组件的引用。
每个vue组件实例上,都包含一个$refs对象,里面存储着DOM元素或组件的引用。
默认情况下,组件的$refs指向一个空对象。
使用ref引用DOM元素
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <template> <h3 ref="myh3">MyRef组件</h3> <button @click="getRef">获取$ref引用</button> </template>
<script> methods: { getRef() { 通过 this.$refs.引用名称 可以获取到DOM元素引用 console.log(this.$refs.myh3) //操作DOM元素 this.$refs.myh3.style.color = 'red' } } </script>
|
使用ref引用组件实例
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <template> <my-counter ref="counterRef">MyRef组件</my-counter> <button @click="getRef">获取$ref引用</button> </template>
<script> methods: { getRef() { 通过 this.$refs.引用名称 可以获取到组件引用 console.log(this.$refs.counterRef) //引用组件后,可以调用组件上的method方法 this.$refs.counterRef.add() } } </script>
|