子組件可以使用$emit調(diào)用父組件的方法并傳遞數(shù)據(jù)
示例
子組件:
<template>
<div>
<button @click="sendMsgToParent">向父組件傳值</button>
</div>
</template>
<script>
export default {
methods: {
sendMsgToParent:function () {
this.$emit("childMsg","hello world!");
}
}
}
</script>
父組件:
<template>
<div id="app">
//@childMsg 與子組件中this.$emit("childMsg","hello world!")起的名字一致
<child @childMsg="showChildMsg"></child>
</div>
</template>
<script>
import child from './components/Child'
export default {
name: "app",
components: {
child
},
methods:{
showChildMsg:function (data) {
console.log(data);
}
}
}
</script>