当前位置: 首页 > article >正文

Vue——认识day05_监视属性

目录

1.天气案例介绍以及初步实现

2.监视属性天气案例的实现

3.深度监视

4.监视的简写形式

5.姓名案例的监视属性实现

6.watch和computed对比



1.天气案例介绍以及初步实现

        这段代码实现了一个简单的天气选择功能。页面中有一个标题和一个按钮,点击按钮可以切换天气的显示。默认显示晴天,点击按钮后会切换到雨天,并在副标题中显示当前选择的天气。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>天气案例</title>

    <script type="text/javascript" src="../js/vue.js"></script>
</head>
</head>
<body>
    <body>

    <div id="root">
        <h1>你是喜欢晴天还是雨天</h1>
        <h2>我喜欢{{weatherInfo}}天</h2>
        <button @click="changeWeather">切换天气</button>
        <!-- <button @click="weather = !weather">切换天气</button> -->
    </div>
    
</body>

<script type="text/javascript">
    Vue.config.productionTip=false
    new Vue({
        el:'#root',
        data:{
            // true代表为晴天晴天,否则为雨天
            weather:true
        },
        computed:{
            weatherInfo(){
                return this.weather?'晴':'雨'
            }
        },
        methods: {
            changeWeather(){
                this.weather = !this.weather
            }
        },
    });
</script>
</html>

2.监视属性天气案例的实现

监视属性watch:

  1. 当被监视的属性变化时,回调函数会自动调用,可以在回调函数中进行相关操作。
  2. 要进行监视的属性必须存在,才能进行监视。
  3. 监视属性有两种写法: (1) 在创建Vue实例时传入watch配置对象,其中键是被监视的属性名称,值是对应的回调函数。 (2) 通过vm.$watch方法来监视属性,需要传入被监视的属性名称和回调函数。

代码示例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>天气案例</title>

    <script type="text/javascript" src="../js/vue.js"></script>
</head>
</head>
<body>
    <body>

    <div id="root">
        <h1>你是喜欢晴天还是雨天</h1>
        <h2>我喜欢{{weatherInfo}}天</h2>
        <button @click="changeWeather">切换天气</button>
    </div>
    
</body>

<script type="text/javascript">
    Vue.config.productionTip=false
    const vm = new Vue({
        el:'#root',
        data:{
            // true代表为晴天晴天,否则为雨天
            weather:true
        },
        // 监视属性
        watch:{
            weather:{
                // 初始化时让handler被触发
               immediate:true,
                // 当weather发生改变的时候被调用
               handler(newValue,oldValue){
                console.log('weather:',oldValue,'被修改为了',newValue)
               } 
            }
        },
        computed:{
            weatherInfo(){
                return this.weather?'晴':'雨'
            }
        },
        methods: {
            changeWeather(){
                this.weather = !this.weather
            }
        },
    });

    // 第二种实现监视的方法
/*     vm.$watch('weather',{
                // 初始化时让handler被触发
                immediate:true,
                // 当weather发生改变的时候被调用
                handler(newValue,oldValue){
                console.log('weather:',oldValue,'被修改为了',newValue)
               }  
    }) */
</script>
</html>

3.深度监视

        深度监视是指在Vue中使用watch来监测对象内部值的改变。默认情况下,Vue的watch只会监测对象的第一层属性变化。但是可以通过配置deep:true来实现对对象内部值的多层监测。需要注意的是,Vue自身是可以监测对象内部值的改变的,但是Vue提供的watch默认是不会进行深度监视的。在使用watch时,根据数据的具体结构决定是否需要采用深度监视。

代码示例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>天气案例</title>

    <script type="text/javascript" src="../js/vue.js"></script>
</head>
</head>
<body>
    <body>

    <div id="root">
        <h1>你是喜欢晴天还是雨天</h1>
        <h2>我喜欢{{weatherInfo}}天</h2>
        <button @click="iLikeYou">心中的秘密</button>
        <button @click="changeWeather">切换天气</button>
        <hr>
        <h3>a:{{numbers.a}}</h3>
        <button @click="numbers.a++">点我a+1</button>
        <br>
        <h3>b:{{numbers.b}}</h3>
        <button @click="numbers.b++">点我b+1</button>
    </div>
    
</body>

<script type="text/javascript">
    Vue.config.productionTip=false
    const vm = new Vue({
        el:'#root',
        data:{
            // true代表为晴天晴天,否则为雨天
            weather:true,
            numbers:{
                a:1,
                b:1
            }
        },
        // 监视属性
        watch:{
            weather:{
                // 初始化时让handler被触发
            //    immediate:true,
                // 当weather发生改变的时候被调用
               handler(newValue,oldValue){
                console.log('weather:',oldValue,'被修改为了',newValue)
               } 
            },
            // 监视多级结构某个属性的变化
/*             'numbers.a':{
                handler(){
                    console.log('a改变了')
                }
            } */
           numbers:{
            // 开启即可监视多级结构中所有属性的变化
            deep:true,
            handler(){
                console.log('numbers改变了')
            }
           }
        },
        computed:{
            // 计算属性
            weatherInfo(){
                return this.weather?'晴':'雨'
            }
        },
        methods: {
            changeWeather(){
                this.weather = !this.weather
            },
            iLikeYou(){
                alert('我喜欢你(๑′ᴗ‵๑)I Lᵒᵛᵉᵧₒᵤ❤')
            }
        },
    });

    // 第二种实现监视的方法
/*     vm.$watch('weather',{
                // 初始化时让handler被触发
                immediate:true,
                // 当weather发生改变的时候被调用
                handler(newValue,oldValue){
                console.log('weather:',oldValue,'被修改为了',newValue)
               }  
    }) */
</script>
</html>

4.监视的简写形式

具体如代码中所示:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>天气案例</title>

    <script type="text/javascript" src="../js/vue.js"></script>
</head>
</head>
<body>
    <body>

    <div id="root">
        <h1>你是喜欢晴天还是雨天</h1>
        <h2>我喜欢{{weatherInfo}}天</h2>
        <button @click="iLikeYou">心中的秘密</button>
        <button @click="changeWeather">切换天气</button>
    
    </div>
    
</body>

<script type="text/javascript">
    Vue.config.productionTip=false
    const vm = new Vue({
        el:'#root',
        data:{
            // true代表为晴天晴天,否则为雨天
            weather:true,
        },
        // 监视属性
        watch:{
            // 正常写法
/*             weather:{
                // 初始化时让handler被触发
            //    immediate:true,
               // 深度监视
            //    deep:true,
                handler(newValue,oldValue){
                console.log('weather:',oldValue,'被修改为了',newValue)
               } 
            }, */
            // 简写的前提就是没有其他的配置项
/*             weather(newValue,oldValue){
                console.log('weather:',oldValue,'被修改为了',newValue)
            } */
        },
        computed:{
            // 计算属性
            weatherInfo(){
                return this.weather?'晴':'雨'
            }
        },
        methods: {
            changeWeather(){
                this.weather = !this.weather
            },
            iLikeYou(){
                alert('我喜欢你(๑′ᴗ‵๑)I Lᵒᵛᵉᵧₒᵤ❤')
            }
        },
    });

    // 第二种实现监视的方法,完整写法
/*     vm.$watch('weather',{
                // 初始化时让handler被触发
                immediate:true,
                // 当weather发生改变的时候被调用
                handler(newValue,oldValue){
                console.log('weather:',oldValue,'被修改为了',newValue)
               }  
    }) */

    // 简写
   vm.$watch('weather',function(newValue,oldValue){
    console.log('weather:',oldValue,'被修改为了',newValue)
   })
</script>
</html>

5.姓名案例的监视属性实现

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>姓名案例_监视属性实现</title>

    <script type="text/javascript" src="../js/vue.js"></script>
</head>
</head>
<body>

    <div id="root">
        姓:<input type="text" v-model="firstName">
        <br><br>
        名:<input type="text" v-model="lastName">
        <br><br>
        全名:<span>{{fullName}}</span>
        <br><br>
    </div>
    </div>
    
</body>

<script type="text/javascript">
    Vue.config.productionTip=false
    const vm = new Vue({
        el:'#root',
        data:{
            firstName:'W',
            lastName:'J',
            fullName:'W-J'
        },
        // 计算属性
        computed:{
        },
        // 监视属性
        watch:{
            firstName:{
                handler(newFirstName){
                    this.fullName = newFirstName + '-' + this.fullName.split('-')[1]
                }
            },
            lastName:{
                handler(newLastName){
                    this.fullName = this.firstName + '-' + newLastName
                }
            }
        }
    });
</script>
</html>

6.watch和computed对比

computed和watch在功能上有一些相似之处,但也有一些区别。首先,computed可以完成watch的功能,但是watch能完成的功能,computed不一定能完成。例如,watch可以进行异步操作,而computed不适合进行异步操作。

另外,有两个重要的原则需要注意:

  1. 对于被Vue所管理的函数,最好写成普通函数,这样函数内部的this指向的是Vue实例对象或组件实例对象。
  2. 对于不被Vue所管理的函数,比如定时器的回调函数、ajax的回调函数、Promise的回调函数等,最好写成箭头函数,这样函数内部的this指向的也是Vue实例对象或组件实例对象。

这样可以确保在函数中使用this时,能够正确地指向Vue实例对象或组件实例对象。



http://www.kler.cn/news/284206.html

相关文章:

  • 安装jmeter的梯度压测线程组(Custom Thread Groups)的插件
  • 10款必备的电脑监控软件推荐,实用又方便!顶尖产品一网打尽!2024纯干货
  • 【JAVA入门】Day28 - 数据结构
  • JavaScript 中,不同的赋值方式适用场景
  • OpenAI“草莓项目”最快今年秋季发布!苹果将于9月10号推出首款AI iPhone|AI日报
  • C/C++ 编译过程概述
  • 睡岗检测数据集(工作 课堂等) 3100张 增强 睡岗趴睡 带标注 voc yolo
  • Springboot3整合ELK实现日志可视化
  • Spring Boot中Tomcat、Jetty、Undertow哪个嵌入式服务器最好?
  • 线性代数基础
  • 实训day29(8.15)
  • 探索未知,悦享惊喜 —— 您的专属盲盒小程序,即将开启奇妙之旅
  • Qt窗口 菜单栏 QMenuBar和的使用及说明
  • 全局页面数据渲染--SAAS本地化及未来之窗行业应用跨平台架构
  • 手机二要素api接口是什么?怎么对接使用?
  • FFmpeg的入门实践系列六(编程入门之常见处理流程)
  • 生信机器学习入门3 - Scikit-Learn训练机器学习分类感知器
  • 巧用scss实现一个通用的媒介查询代码
  • Java算法之希尔排序(Shell Sort)
  • 09:Logic软件原理图信号连通
  • LuaJit分析(九)LuaJit中的JIT原理分析
  • Codeforces Round 969 (Div. 2 ABCDE题) 视频讲解
  • 热门跨境平台的IP代理如何选择?入局IP知识
  • Python编写BC260Y TCP数据收发压力测试脚本
  • 创建SQLiteOpenHelper 类来创建和管理SQLite数据库
  • vue2踩坑记录:el-select如何绑定对象
  • 二叉树详解(2)
  • Ethercat设备数据 转IEC61850项目案例
  • zyx青岛实训day34 初步了解Docker与套接字的应用
  • 行为模式7.解释器模式------DSL语言