主要用到ref,父组件获取子组件的ref执行子组件内的方法
子组件
<template>
<div>
<p>{{info}}</p>
<button @click="cancelInfo">Cancel</button>
</div>
</template>
<script>
export default {
name: 'InfoButon',
data(){
return{
info: 'ModifyInfo'
}
},
methods:{
cancelInfo(){
console.log('');
this.info = 'Init-Info'
}
}
}
</script>
父组件
<template>
<div>hello PageTech-{{title}}
<button @click="getTitle">getTitle</button>
<InfoButon ref="infoButtonRef" />
</div>
</template>
<script>
import InfoButon from "./components/InfoButton/index.vue";
export default {
name: 'PageTect',
components:{
InfoButon
},
data() {
return {
title: 'Title-title'
}
},
//
mounted(){
console.log('mounted');
},
methods:{
getTitle(){
console.log('title',this.title,this);
// 调用子组件方法
this.$refs.infoButtonRef.cancelInfo();
}
}
}
</script>