前言:有的时候你仍可能需要在 JavaScript 里直接访问一个子组件。为了达到这个目的,你可以通过 ref 为子组件赋予一个 ID 引用,类似于html中的id,
ref
ref 被用来给DOM元素或子组件注册引用信息
$refs
$refs是一个对象,持有已注册过ref的所有的子组件
注意:因为ref本身是作为渲染结果被创建的,在初始渲染的时候你不能访问他们,他们还不存在。另外,$refs也不是响应式的,不能用它在模版中做数据绑定
下面一起来看下几种用法:
(1)获取本页面的DOM元素
<template>
<div>
<h3 ref="getDom">1234</h3>
<button @click="start">获取DOM</button>
</div>
</template>
<script>
export default {
methods: {
start() {
console.log(this.$refs.getDom)
}
},
}
</script>
(2)获取子组件的data
子组件:
//child.vue
<template>
<div>
{{msg}}
</div>
</template>
<script>
export default {
data() {
return {
msg: '我是子组件'
}
},
}
</script>
父组件:
<template>
<div>
我是父组件
<child ref="getRef"></child>
<button @click="start">点击获取子组件的data</button>
</div>
</template>
<script>
import child from './child/child'
export default {
components: {
child
},
methods: {
start() {
console.log(this.$refs.getRef.msg)
}
},
}
</script>
(3)调用子组件的方法
子组件:
//child.vue
<template>
<div>
</div>
</template>
<script>
export default {
methods: {
start() {
console.log('我是子组件的方法')
}
},
}
</script>
父组件:
<template>
<div>
我是父组件
<child ref="getRef"></child>
<button @click="toGetMethods">点击获取子组件的方法</button>
</div>
</template>
<script>
import child from './child/child'
export default {
components: {
child
},
methods: {
toGetMethods() {
this.$refs.getRef.start()
}
},
}
</script>
(4)子组件调用父组件的方法
子组件:
//child.vue
<template>
<div>
</div>
</template>
<script>
export default {
methods: {
open() {
this.$emit("refresh")
}
},
}
</script>
父组件:
<template>
<div>
<child @refresh="start" ref="getRef"></child>
<button @click="REF">点击获取子组件的方法</button>
</div>
</template>
<script>
import child from './child/child'
export default {
components: {
child
},
methods: {
REF() {
this.$refs.getRef.open()
},
start() {
console.log('我是父组件的方法')
}
},
}
</script>