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>

使用单标签引用组件时,效果图:

 

使用双标签引用组件时,效果图:

猜你喜欢

转载自www.cnblogs.com/taohuaya/p/10233033.html
今日推荐