父组件中通过$ref获取子组件的实例,调用子组件的方法,修改子组件的样式
父组件:
<script>
import ChildComp from './ChildComp.vue'
export default {
components: {
ChildComp
},
mounted(){
this.$refs.testcy.fn();
console.log(this.$refs.testcy)
},
methods:{
increase(){
//1、调用子组件的方法
this.$refs.testcy.fn();
// console.log(this.$refs.testcy.$el.classList)
//2、修改子组件的样式
if(this.$refs.testcy.$el.classList.contains('test03')){
this.$refs.testcy.$el.classList.remove('test03')
}else{
this.$refs.testcy.$el.classList.add('test03')
}
}
}
}
</script>
<template>
<div>
<ChildComp ref='testcy'/>
<button @click='increase'>
+
</button>
</div>
</template>
<style scoped>
.test03{
color:red;
}
</style>
子组件:
<template>
<h2 :class="['class01','class02']">A Child Component!{{num}}</h2>
</template>
<script>
export default{
data(){
return {
num:0
}
},
methods:{
fn(){
this.num++;
}
}
}
</script>