Reputation: 3440
I am using vue.js for a small web app. The whole content is wrapped in a div#app
. How can I trigger a function outside of #app
?
var app = new Vue({
el: '#app',
data: {
message: 'I am a working vue app'
},
methods: {
showAlert: function() {
alert("Hello world");
}
}
})
<html>
<head>
<script src="https://unpkg.com/vue"></script>
</head>
<body>
<div id="app">
{{ message }}
<button v-on:click="showAlert">Alert</button>
</div>
<button v-on:click="showAlert">Alert not working</button>
</body>
</html>
Upvotes: 3
Views: 267
Reputation: 82459
In your case, the alert is not going to work because Vue is only going to do anything with the code inside it's template. You've identified the template as #app
, so the only HTML that Vue is concerned with is
<div id="app">
{{ message }}
<button v-on:click="showAlert">Alert</button>
</div>
That being the case, you've defined a Vue specific means of attaching an event handler to code elsewhere in your HTML.
<button v-on:click="showAlert">Alert not working</button>
The reason it doesn't work is because Vue doesn't even know that code exists. It is not inside #app
.
If you wanted to trigger the alert from outside, you can use any plain javascript method for attaching an event handler to your button and call the method. For example,
<button onclick="app.showAlert()">Alert not working</button>
Note: You probably shouldn't set both the id
and the variable that captures the result of new Vue()
to the same name, app
. In most browsers, the id
of HTML elements are exposed in the global scope and you now have two variables named app
. In this case, the Vue wins, but you can easily change it to something like
var myApp = new Vue({...})
to spare confusion. If you did that, the line above would be
<button onclick="myApp.showAlert()">Alert not working</button>
Upvotes: 2