vue自定义事件?

<!DOCTYPE html>
<html lang="en" xmlns:v-bind="http://www.w3.org/1999/xhtml" xmlns:v-on="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="UTF-8">
    <title>自定义事件</title>
    <script src="https://cdn.bootcss.com/vue/2.4.2/vue.min.js"></script>
</head>
<body>
    <div id="app">
        <button v-on:click="f1">click</button>
        <button v-on:click="f2" v-on:test2="f3">click1</button>
    </div>
    <div id="counter-event-example">
        <p>{{ total }}</p>
        <button-counter v-on:increment="incrementTotal"></button-counter>
        <button-counter v-on:increment="incrementTotal"></button-counter>
    </div>
    <script>
        var vm = new Vue({
            el: "#app",
            data: {
                msg: "hello"
            },
            methods: {
                f1: function () {
                    alert( this.msg );
                    this.$emit('test');
                },
                f2: function () {
                    this.$emit('test2');
                },
                f3: function () {
                    alert('ok');
                }
            }
        });
        vm.$on('test', function () {
            console.log(this.msg)
        });
        /*---官网上的--*/
        Vue.component('button-counter', {
            template: '<button v-on:click="incrementCounter">{{ counter }}</button>',
            data: function () {
                return {
                    counter: 0
                }
            },
            methods: {
                incrementCounter: function () {
                    this.counter += 1
                    this.$emit('increment')
                }
            },
        })
        new Vue({
            el: '#counter-event-example',
            data: {
                total: 0
            },
            methods: {
                incrementTotal: function () {
                    this.total += 1
                }
            }
        })
    </script>
</body>
</html>

第一个按钮我写了自定义事件,click的时候触发了事件,成功执行。第二个按钮是按照官网的想法写的,区别也就是官网是使用在子组件上吧,为什么不执行呢?

阅读 2k
2 个回答

emit触发事件是在父组件上进行监听的 v-on:click="f2" 里面触发的事件应该在button的父组件监听,button已经没有父组件了,需要直接在实例vm上进行监听,也就是f2中的this就是vm,所以需要vm.$on进行监听,你的f3是监听不到的,可以参考实例事件

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题