Vue 中 ref 的使用
Vue2 中使用 ref
父组件
<template>
<hello-world ref='son'></hello-world>
<button @click='getSon'>获取</button>
</template>
<script>
import HelloWorld from './components/HelloWorld.vue'
export default {
components: {
HelloWorld
},
data() {
return {
}
},
methods: {
getSon() {
// 父组件获取子组件的属性和调用子组件的方法
console.log(this.$ref.son.title)
this.$ref.son.sonMethod()
}
}
}
</script>子组件
<template>
<div> {{ title }} </div>
</template>
<script>
export default {
name: 'Son',
data() {
return {
title: '我是子组件的标题'
}
},
methods: {
sonMethod() {
console.log('我是子组件的方法')
}
}
}
</script>
评论 (0)