qwq 前两天看了下vue,父子组件方法的调用,怕忘记,所以做个小记录。
一.父组件调用子组件的方法
1.父组件
<template>
<div id="rightmenu8">
<rightmenu7 ref="rightmenu7"></rightmenu7> // ref要放在组件上
<button @click="parent1">+</button>
<button @click="parent2">-</button>
<span>{{age}}</span>
</div>
</template>
<script>
import rightmenu7 from "./RightMenu7.vue";//引入子组件
export default {
name: "rightmenu8",
data() {
return {
age:18
}
},
methods: {
parent1(){ //调用子组件的方法
this.$refs.rightmenu7.add();// add子组件方法
},
parent2(){
this.$refs.rightmenu7.miute(); //miute子组件方法
}
},
components: {//注册子组件
rightmenu7: rightmenu7
}
};
</script>
2子组件
<template>
<div id="rightmenu7" >
<span>{{wendu}}℃</span>
<span>{{chuanyi}}</span>
</div>
</template>
<script>
export default {
name:"rightmenu7",
data(){
return{
wendu:17,
chuanyi:'长袖衫'
}
},
methods:{
add(){
this.wendu+=2;
},miute(){
this.wendu-=2;
}
},
watch:{ //实时监控wendu值变化
wendu(newData,oldData){
if(newData<17){
this.chuanyi="棉袄"
}else if(newData==17){
this.chuanyi="长袖衫"
}else{
this.chuanyi="大裤衩";
}
}
}
}
</script>
<style>
</style>