Same time I got an another error, which is "Invalid handler for event "click"".
<template>
<div id="example-2">
<!-- `greet` is the name of a method defined below -->
<button v-on:click="greet">Greet</button>
</div>
</template>
<script>
window.onload = function () {
var example2 = new Vue({
el: '#example-2',
data: {
name: 'Vue.js'
},
// creating method greet
methods: {
greet: function (event) {
// `this` inside methods points to the Vue instance
alert('Hello ' + this.name + '!')
// `event` is the native DOM event
if (event) {
alert(event.target.tagName)
}
}
}
})
}
</script>
the template
tag is hidden when the HTML loads so you get the error cannot find element
or something like that. You can load it with javascript.
Vue.js does not use the built in template
tag.
However if you using it over cdn try it like this
<div id="example-2">
<button v-on:click="greet">Greet</button>
</div>
<script>
var example2 = new Vue({
el: "#example-2",
data: {
name: "Vue.js",
},
methods: {
greet: function(event) {
alert("Hello " + this.name + "!");
if (event) {
alert(event.target.tagName);
}
},
},
});
</script>
What you can simply do is remove the template
tags
Here is the working code: https://jsfiddle.net/t49zxdov/2/
<div id="example-2">
<!-- `greet` is the name of a method defined below -->
<button v-on:click="greet">Greet</button>
</div>
window.onload = function () {
var example2 = new Vue({
el: '#example-2',
data: {
name: 'Vue.js'
},
// creating method greet
methods: {
greet: function (event) {
// `this` inside methods points to the Vue instance
alert('Hello ' + this.name + '!')
// `event` is the native DOM event
if (event) {
alert(event.target.tagName)
}
}
}
})
}
You should separate your vue template and the vue instance. To do that,
create file, ex: example.vue
copy this code
<template>
<div id="example-2">
<!-- `greet` is the name of a method defined below -->
<button v-on:click="greet">Greet</button>
</div>
</template>
<script>
data() {
return {
name: 'Vue.js'
}
},
methods: {
greet: function (event) {
// `this` inside methods points to the Vue instance
alert('Hello ' + this.name + '!')
// `event` is the native DOM event
if (event) {
alert(event.target.tagName)
}
}
}
</script>
and create this file, ex: app.js
const app = new Vue({
el: '#example-2',
});
and then link your app.js
to your index layout.
I hope you get my point. thanks
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.