Vue中使用Vue.component定義兩個全局組件,用單標簽應用組件時,只顯示一個組件的問題和 $emit的使用。


解決方法:  

定義了兩個 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>

使用單標簽引用組件時,效果圖:

 

 

使用雙標簽引用組件時,效果圖:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM