子元素觸發父元素事件四步走
- 子組件定義一個事件,或者寫在生命周期里面
- 子組件方法內(生命周期內),觸發父元素事件 this.$emit("方法名",參數);
- 把子組件引入父組件內,<子組件 @方法名=“父組件內方法”></子組件>
注意,父組件內‘@方法名’要與
子組件內this.$emit("方法名",參數),兩個方法名保持一致 - 父組件內方法自己的邏輯
子組件 child.vue
<template>
<div>
<button @click="clickMe">
點擊我觸發事件
</button>
</div>
</template>
<script>
export default{
data(){
return{}
}
methods:{
clickMe(){
//此處的cccc要與父組件的保持一致
this.$emit("cccc",param)
}
}
}
</script>
父組件
<template>
<div>
//此處的cccc要與子組件的保持一致
<vChild @cccc="parentMethods"></vChild>
</div>
</template>
<script>
import vChild from './child.vue'
export default{
data(){
return{}
},
components:{
vChild
},
methods:{
parentMethods(param){
console.log(param);
//do someThing
}
}
}
</script>
除此之外還有一種比較直接的方法
- 新建一個js文件
- 子組件引入新建的bus
- 用bus觸發
on方法
bus.js
import Vue from 'vue'
export var bus = new Vue()
子組件
<template>
<div @click="pass">
表單傳值
</div>
</template>
<script>
import {bus} from '../../../utils/bus'
export default {
name: "Child",
data() {
return {}
},
components: {},
mounted() {
},
methods: {
pass(){
alert("1112")
bus.$emit("father",'admin');
},
},
}
</script>
<style scoped>
</style>
父組件
<template>
<div>
<pass-child></pass-child>
<div>
父子傳值
</div>
</div>
</template>
<script>
import PassChild from './Child'
import {bus} from '../../../utils/bus'
export default {
name: "PassIndex",
data() {
return {}
},
components: {
PassChild
},
mounted() {
bus.$on('father',(param)=>{
console.log(param)
})
},
methods: {},
}
</script>
<style scoped>
</style>