<!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的时候触发了事件,成功执行。第二个按钮是按照官网的想法写的,区别也就是官网是使用在子组件上吧,为什么不执行呢?
https://jsfiddle.net/tajxy1d6/
没有不执行呀。。。