One of the chief differences is scope access. onclick
's bound scope is global so the functions that you want it to call have to be accessible from the global scope. v-on
's scope is the Vue model.
Another thing is that Vue provides a very easy API to define custom events through vm.$emit()
. It's also very easy to listen for those events using v-on:customevent="callback"
which can be easily cognitively mapped to a hypothetical onfizz="callback()"
.
With that in mind, it makes sense to also provide v-on:click
for a consistent API as well as the other extensions v-on
provides.
function onClickGlobal() {
console.log("global");
}
const fizzbuzz = {
template: "<button @click='onClick'>FizzBuzz</button>",
methods: {
onClick() {
this.$emit("fizz");
}
}
};
const app = new Vue({
el: "#app",
components: {
fizzbuzz
},
methods: {
onClickModel() {
console.log("model");
},
onFizz() {
console.log("heard fizz");
}
}
});
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<div id="app">
<section>
<h2>Buttons and Clicks</h2>
<button @click="onClickModel">v-on Model</button>
<button @click="onClickGlobal">v-on Global</button>
<button onclick="onClickModel()">onclick Model</button>
<button onclick="onClickGlobal()">onclick Global</button>
<button onclick="app.onClickModel()">onclick Global through app.onClickModel</button>
</section>
<section>
<h2>Custom Events</h2>
<fizzbuzz @fizz="onFizz"></fizzbuzz>
<button onfizz="onClickGlobal">Hypothetical Fizz</button>
</section>
</div>
v-on
and the native DOM API'sonclick
. The post you linked is not about that. – zero298v-on:
notation can be used not just for native DOM events but for application-defined vue events, thus you gain consistency. 2.)v-on:
handlers can be defined not just on DOM nodes but on vue components. – collapsar