首页 > 技术文章 > vue v-on事件监听

zhangcheng001 2019-09-06 10:58 原文

通过点击按钮,实现背景色的循环变换

 

 初始为红色,点击一次,变成蓝色,第二次变成绿色,再次点击,又变为红色

这里用到vue的事件监听 v-on:xxx 

事件写在methods里面

代码部分

<!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>vue-test3</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>
    <style>
    .red{
        background: red;
    }
    .blue{
        background: blue;
    }
    .green{
        background: green;
    }
    </style>
</head>

<body>
    <div id="test">
        <button v-on:click="clickFun()">点击</button>
        <p :class="classAttr[index]">改变背景色</p>
    </div>

    <script>
        const vm = new Vue({
            el: '#test',
            data: {
                classAttr: ['red', 'blue', 'green'],
                index: 0,
                count: 0
            },
            methods: {
                clickFun() {
                    // this = vm this就是vue实例对象 获取data里的数据
                    this.index = ++this.count % 3

                }
            }
        })
    </script>
</body>

</html>

v-on可以简写成@ 效果一样

<button @click="clickFun()">点击</button>

 

推荐阅读