提示

本文主要讲解 Vue 中的监听属性。@ermo

# 监听属性

监听属性的关键词是 watch,用于数据量较大的计算或者异步执行时对数据的响应。

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.7.14"></script>
</head>

<body>
    <div id="app">
        <p>累加器:{{counter}}</p>
        <p>{{msg}}</p>
        <button @click="add">点击</button>
    </div>
    <script>
        var vm = new Vue({
            el: '#app',
            data: {
                counter: 1,
                msg: ''
            },
            methods: {
                add: function () {
                    return this.counter++;
                }
            }
        });

        vm.$watch('counter', function (newVal, oldVal) {
            alert('旧值:' + oldVal + ',新值:' + newVal);
        });
    </script>
</body>

</html>

下面是一个时分秒换算的例子。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.7.14"></script>
</head>
<body>
    <div id="app">
        小时:<input type="text" v-model="hours">
        分钟:<input type="text" v-model="minutes">
        秒:<input type="text" v-model="seconds">
        <p id="info"></p>
    </div>

    <script>
        var vm = new Vue({
            el: '#app',
            data: {
                hours: 0,
                minutes: 0,
                seconds: 0
            },
            computed: {

            },
            watch: {
                hours: function(val) {
                    this.minutes = val * 60;
                    this.seconds = val * 60 * 60;
                },
                minutes: function(val) {
                    this.hours = val / 60;
                    this.seconds = val * 60;
                },
                seconds: function(val) {
                    this.minutes = val / 60;
                    this.hours = this.minutes / 60;
                }
            }
        });
        vm.$watch('hours', function(newVal, oldVal) {
            document.getElementById('info').innerHTML = '小时修改前值:' + oldVal + ",修改后值:" + newVal;
        });
    </script>
</body>
</html>
上次更新: 2/20/2023, 6:45:13 AM