解決方法:
定義了兩個 Vue.component 在 el 中使用的時候要用 雙標簽, 用單表標簽的時候,只會顯示第個 組件間
這樣寫只顯示 welcome-button 組件
<welcome-button @welcome="sayHi"/>
<magic-eight-ball @give-advice="showAdvice"/>
--------------------------------
改成雙標簽后,就會顯示兩個組件了。
<welcome-button @welcome="sayHi"></welcome-button>
<magic-eight-ball @give-advice="showAdvice"></magic-eight-ball>
完整代碼:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>$emit</title> <script src="node_modules/vue/dist/vue.min.js"></script> </head> <body> <div id="app"> <welcome-button @welcome="sayHi"></welcome-button> <magic-eight-ball @give-advice="showAdvice"></magic-eight-ball> </div> <script> /* 注: 定義了兩個 Vue.component 在 el 中使用的時候要用 雙標簽, 用代表標簽的換,只會顯示第個 組件間 這樣寫只顯示 welcome-button 組件 <welcome-button @welcome="sayHi"/> <magic-eight-ball @give-advice="showAdvice"/> -------------------------------- 改成雙標簽后,就會顯示兩個組件了。 <welcome-button @welcome="sayHi"></welcome-button> <magic-eight-ball @give-advice="showAdvice"></magic-eight-ball> */ /*---------------無參數---------------------*/ Vue.component('welcome-button', { template: `<button v-on:click="$emit('welcome')"> 點我 </button>` }); /*-----------------有參數---------------*/ Vue.component('magic-eight-ball', { data: function () { return { possibleAdvice: ['Yes', 'No', 'Maybe'] } }, methods: { giveAdvice: function () { var randomAdviceIndex = Math.floor(Math.random() * this.possibleAdvice.length); // console.log( this.possibleAdvice[randomAdviceIndex]); this.$emit('give-advice', this.possibleAdvice[randomAdviceIndex]) } }, template: ` <button v-on:click="giveAdvice"> 點我出發父組件的方法,並傳參 </button>` }) new Vue({ el: '#app', methods: { sayHi(){ alert('Hi!'); }, showAdvice(advice){ alert(advice) } }, }); </script> </body> </html>
使用單標簽引用組件時,效果圖:
使用雙標簽引用組件時,效果圖: