ref 加在标签上 this.$refs是拿到dom , 若ref加上组件上this.$refs拿到的是组件的引用
子组件B
<template>
<div class="con">
<p @click="add">{{num}}</p>
</div>
</template>
<script type="text/ecmascript-6">
export default {
data() {
return {
num: 0
}
},
methods: {
add() {
this.num ++
this.$emit('change')
}
},
}
</script>
<style>
.con p:first-child{
background-color: pink;
}
</style>
父组件
<template>
<div>
<div ref='d' @click="setColor">hello </div>
<row ref='one' @change='change1'></row>
<row ref='two' @change='change1'></row>
<p>{{totla}}</p>
</div>
</template>
<script type="text/ecmascript-6">
import b1 from './B'
export default {
data() {
return {
num: 0,
totla: 0
}
},
methods: {
setColor() {
let d = this.$refs.d
d.style.color = 'red'
},
change1() {
let two= this.$refs.two
console.log(two); //拿到的是组件的引用
this.totla = this.$refs.one.num + this.$refs.two.num
}
},
components: {
row: b1
}
}
还能控制子组件的显示与隐藏,调用子组件的方法及赋值
父组件
<template>
<div>
<p @click="go">go</p>
<com-button ref='com'></com-button>
</div>
</template>
<script>
import comButton from './comButton.vue';
export default {
data() {
return {
}
},
components: {
comButton,
},
methods: {
go() {
let res = 888
this.$refs.com.isShow = true
this.$refs.com.val = res
this.$refs.com.name()
this.$refs.com.open('777')
this.$refs.com.open(['333'])
},
},
}
</script>
<style>
</style>
自组件comButton.vue
<template>
<div v-show="isShow">
this is comButton
<p style="color:red;">父组件传来的值{{val}}</p>
<p style="color:red;">父组件传来的值{{data}}</p>
</div>
</template>
<script>
export default {
data() {
return {
isShow: false,
val: '',
data: []
}
},
methods: {
name() {
console.log('被调了')
},
open(data) {
console.log(typeof data)
this.data = data
}
},
}
</script>
<style>
</style>
效果图