給子組件注冊一個ref=“childname”
然后可在父組件中用
this.$refs.childname.functionname() 調用子組件方法
例子:父組件
<template> <div id="app"> <!--父組件--> <input v-model="msg" /> <button v-on:click="notify">廣播事件</button> <!--子組件--> <popup ref="child"></popup> </div> </template> <script> import popup from "@/components/popup"; export default { name: "app", data: function () { return { msg: "", }; }, components: { popup, }, methods: { notify: function () { if (this.msg.trim()) { this.$refs.child.parentMsg(this.msg); } }, }, }; </script> <style> #app { font-family: "Avenir", Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>
子組件
<template> <div> <ul> <li v-for="item in messages">父組件輸入了:{{ item }}</li> </ul> </div> </template> <style> body { background-color: #ffffff; } </style> <script> export default { name: "popup", data: function () { return { messages: [], }; }, methods: { parentMsg: function (msg) { this.messages.push(msg); }, }, }; </script>
