监视

1、案例1

<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Title of the document</title>
</head>

<body>
    <div id="app">
        <!--fullName的值需要根据firstName和lastName的值拼接而成-->
        firstName:<input type="text" v-model="firstName"></input><br>
        lastName:<input type="text" v-model="lastName"></input><br>
        fullName:<input type="text" v-model="fullName"></input>
    </div>
    <script src="../js/vue.js" type="text/javascript"></script>
    <script>
        const vm = new Vue({
            el: "#app",
            data: {
                firstName: "A",
                lastName: "B",
                fullName: ""
            },
            watch: {
                //通过配置的方法使用监视
                //监视firstName的值
                //监视属性的方法在属性值初始化的时候不会被执行(与计算属性方法不同)
                //当被监视的属性值有改变时就会执行监视属性的方法
                firstName(newValue, oldValue) {
                    this.fullName = newValue + " " + this.lastName;
                }
            }
        });
        //通过直接调用方法的方式使用监视
        //监视lastName属性值的改变,若有改变则会执行此方法
        //属性值初始化的时候不会执行此方法
        vm.$watch("lastName", function (newValue, oldValue) {
            this.fullName = this.firstName + " " + newValue;
        });
    </script>
</body>

</html>

猜你喜欢

转载自www.cnblogs.com/liuyang-520/p/12444162.html