Examples of internal components and Vue
Vue instance events
Examples of events: write a method call inside the constructor outside of the constructor, the data may be in the internal structure of an external call to the constructor by such an approach.
$ on () event: Adding an event outside the constructor
$ once event: the event is executed only once
$ off () event: close event, after closing no longer perform
$ On event
$ On accepts two parameters, the first is the event name when called, and the second is an anonymous function (method)
vue实例.$on('事件名称',function(){...})
Examples: click the add button to achieve the value of 1 plus-function, reduce click Save button value to achieve a function.
Define vue constructor:
var demo=new Vue({
el:"#app",
data:{
numbers:1
},
methods:{
add:function(){
this.numbers++;
console.log("执行了add方法")
}
}
})
1.on event method:
Note: reduce call is the name of the event, followed by the anonymous method to achieve a value of minus one function
demo.$on('reduce',function(){
console.log("执行了reduce方法")
this.numbers--;
})
If the button is outside the scope, you can use $emitTo perform
function reduce () {
demo.$emit('reduce')
}
2.once event method:
Note: doOnce is the name of the event to call, followed by the anonymous method to achieve a value of minus one function, which is performed only once.
demo.$once('doOnce',function(){
this.numbers--;
console.log("执行了once方法,只执行一次")
})
If the button is outside the scope, you can use $emitTo perform
function doOnce(){
demo.$emit('doOnce')
}
3.off event method:
Note: off event is closed to execute the program, it can not be executed after closing.
off ( 'closing event of the name')
function off(){
demo.$off('reduce')
console.log("执行了off方法,关闭事件")
}
Complete code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Vue实例事件</title>
<script type="text/javascript" src="../assets/js/vue.js"></script>
</head>
<body>
<h1>vue实例事件</h1>
<div id="app">
数值:{{numbers}}
<p><button @click="add">add</button></p>
</div>
<p><button onclick="reduce()">reduce</button></p>
<p><button onclick="doOnce()">doOnce</button></p>
<p><button onclick="off()">off</button></p>
<script>
var demo=new Vue({
el:"#app",
data:{
numbers:1
},
methods:{
add:function(){
this.numbers++;
console.log("执行了add方法")
}
}
})
demo.$on('reduce',function(){
console.log("执行了reduce方法")
this.numbers--;
})
demo.$once('doOnce',function(){
this.numbers--;
console.log("执行了once方法,只执行一次")
})
function reduce () {
demo.$emit('reduce')
}
function doOnce(){
demo.$emit('doOnce')
}
function off(){
demo.$off('reduce')
console.log("执行了off方法,关闭事件")
}
</script>
</body>
</html>
operation result: