一 获取页面dom元素
<p ref="content">ref可以作为唯一标识</p>
<button @click="hint">提示</button>
methods:{
hint(){
console.log(this.$refs.content);
console.log(this.$refs.content.textContent);
}
}
二 使用子组件中的数据和方法
子组件:
data () {
return {
msg: '获取子组件中的数据'
}
},
父组件:
<hello-world ref="hello"></hello-world>
<button @click="getHello">获取子组件中的数据</button>
methods:{
getHello(){
console.log(this.$refs.hello.msg);
}
}
子组件:
usechild(){
console.log('调用了子组件中的方法');
}
父组件:
getHello(){
this.$refs.hello.usechild()
}
三 使用父组件中的方法
子组件使用$emit
子组件:
<button @click="getFather">获取父组件中的方法</button>
getFather(){
console.log(22222);
this.$emit('refreshData')
}
父组件使用@进行绑定监听,refreshData就是连接父子组件的标志
父组件:
<hello-world ref="hello" @refreshData="getdata"></hello-world>
getdata(){
console.log('调用了父组件的方法');
}