组件通信之子父通信
- 父组件需要通过
v-on
自定义一个事件,子组件需要通过$emit
去触发这个自定义事件,同时也可以把数据发射给父组件
<template>
<div>
<son :msg="info" @onEmit></son>
<p>{{currentIdx}}</p>
</div>
</template>
<script>
import son from './Son.vue'
export default{
name: 'father',
components: {
son
},
data(){
return {
info: ['东', '南', '西', '北'],
currentIdx: 0
}
},
methods: {
onEmit(idx) {
this.currentIdx = idx
}
}
}
</script>
<template>
<div>
<button @click="emitIndex(10)">触发父组件的自定义事件</button>
<p v-for="(item, idx) in info" :key="idx">
{{item}}
</p>
</div>
</template>
<script>
export defalut {
props: ['info'],
methods: {
emitIndex(n){
this.$emit('onEmit', n)
}
}
}
</script>