vue组件:和@区别 冒号和@符号区别

冒号:相当于参数,在组件里面用this.方法名(参数) 直接调用

@符号:相当于事件方法,需要用 this.$emit('方法名', "参数1","参数2"。。。)调用

 

<html>

<head>
    <meta charset="UTF-8">
    <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>

    <script>

        Vue.component('myComponent', {
            props: {
                onFun1: { type: Function }
            },
            methods: {
                componentFun1: function () {
                    if(this.onFun1)this.onFun1("冒号");
                    console.log("-component.fun1.冒号直接调用")
                },
                componentFun2: function () {                    
                    this.$emit('on-fun2', "@符号")
                    console.log("-component.fun1.@符号用$emit调用")
                },
            },
            template: `<span><button @click="componentFun1">fun1</button><button @click="componentFun2">fun2</button></span>`
        });
        </script>
</head>

<body>
    <div id="app">
        <span>{{index}}</span>
        <my-component :on-fun1="fun1"  @on-fun2="fun2"></my-component>
    </div>
    <script>


        var v1 = new Vue({
            el: '#app',
            data: {
                index:0,
            },
            methods: {
                fun1: function (v) {                    
                    this.index++;
                    console.log("-page.fun1."+v);
                },
                fun2: function (v) {
                    this.index++;
                    console.log("-page.fun2."+v);
                },
            }
        })

    </script>
</body>

</html>

 

posted @ 2022-02-07 17:10  为乐而来  阅读(936)  评论(0编辑  收藏  举报