微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

vue 实例事件

好处是在构造器外部增加一个构造器内部事件

有三个实例事件方法

- $on() // 点击一次执行一次

- $once() // 只执行一次

- $off() // 关闭事件方法

外部方法通过 $emit 方法调用

代码示例如下:

<!DOCTYPE html>
<html lang="en">

<head>
<Meta charset="UTF-8">
<Meta name="viewport" content="width=device-width,initial-scale=1.0">
<Meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>example-3</title>
<script src="../assets/js/vue.js"></script>
<script src="../assets/js/jquery-3.1.0.min.js"></script>
</head>

<body>
<h1>example-3</h1>
<hr>
<div id="app">
{{num}}
<p><button @click="add">add</button></p>
</div>
<p><button onclick="reduce()">reduce</button></p>
<p><button onclick="reduceOnce()">reduceOnce</button></p>
<p><button onclick="off()">off</button></p>
<script>
var app = new Vue({
el: ‘#app‘,
data() {
return {
num: 1
}
},
methods: {
add() {
this.num++
}
},
})

app.$on(‘reduce‘,function () {
console.log(‘执行了reduce方法‘);
this.num--
})

app.$once(‘reduceOnce‘,function () {
console.log(‘执行了一次的方法‘);
this.num--
})

function reduce() {
app.$emit(‘reduce‘)
}

function reduceOnce() {
app.$emit(‘reduceOnce‘)
}

function off() {
app.$off(‘reduce‘)
}
</script>
</body>

</html>

分享图片

分享图片

分享图片

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐