search
HomeWeb Front-endJS TutorialThe use of JavaScript computed properties and monitoring (listening) properties

This article brings you relevant knowledge about JavaScript, which mainly introduces the use of calculated properties and monitoring properties. Calculated properties refer to the final result after a series of operations. A value of , the monitor allows developers to monitor changes in data and perform specific operations based on changes in data; let’s take a look at it together, I hope it will be helpful to everyone.

The use of JavaScript computed properties and monitoring (listening) properties

[Related recommendations: JavaScript video tutorial, web front-end]

Calculated properties ( computed)

Computed properties refer toAfter a series of operations, a value is finally obtained. This dynamically calculated attribute value can be used by the template structure or methods method. The case is as follows:

<div>
    R:<input><br>
    G:<input><br>
    B:<input>
    <div>
        {{rgb}}
    </div>
    <button>按钮</button>
</div>
<script></script>
<script>
    const vm = new Vue({
        el:&#39;#root&#39;,
        data:{
            r:0 , g:0, b:0,
        },
        methods: {
            show() {
                console.log(this.rgb);
            }
        },
        //所有计算属性都要定义到computed节点之下
        computed: {
            // 计算属性在定义的时候,要定义成“方法格式”,在这个方法中会生成好的rgb(x,x,x)的字符串
            //实现了代码的复用,只要计算属性中依赖的数据变化了,则计算属性会自动重新赋值
            rgb() {
                return `rgb(${this.r},${this.g},${this.b})`
            }
        }
    })
</script>

Use the name to dynamically change the calculated attribute case:

<div>
    <input><br>
    <input><br>
    全名:<span>{{fullname}}</span>
</div>
<script></script>
<script>
    const vm = new Vue({
        el:"#root",
        data:{
            firstname:&#39;张&#39;,
            lastname:&#39;三&#39;
        },
        computed:{
            fullname:{
                //当初次读取fullname或所依赖的数据发生变化时,get被调用
                get(){
                    console.log(&#39;get被调用了&#39;);
                    return this.firstname+&#39;-&#39;+this.lastname
                },
                //当主动修改fullname时,set被调用
                set(value){
                    console.log(&#39;set&#39;, value);
                    const arr = value.split(&#39;-&#39;);
                    this.firstname = arr[0]
                    this.lastname = arr[1]
                }
            }
        }
    })
</script>

Calculated attribute

1. Definition: The attribute to be used does not exist, and the existing attribute must be passed Properties are obtained

2. Principle: The bottom layer uses the getters and setters provided by the Object.defineproperty method

3. Advantages: Compared with methods implementation, there is an internal caching mechanism (reuse), More efficient and convenient for debugging

4. Note: The calculated attributes will eventually appear on the vm and can be directly read and used; if the calculated attributes are to be modified, the set function must be written to respond to the change, and set In order to cause the data relied upon for calculation to change.

Monitoring properties (watch)

watch monitoring (listener)Allows developers to monitor changes in data, thereby targeting data Changes do specific operations.

Two methods of monitoring

Pass in the watch configuration when passing new Vue:

<div>
    <input>
</div>
<script></script>
<script>
    const vm = new Vue({
        el:&#39;#root&#39;,
        data:{
            name:&#39;&#39;
        },
        //所有的侦听器,都应该被定义到watch节点下
        watch:{
            // 侦听器本质上是一个函数,要监视哪个数据的变化,就把数据名作为方法名即可
            //newVal是“变化后的新值”,oldVal是“变化之前旧值”
            name(newVal,oldVal){ //监听name值的变化
                console.log("监听到了新值"+newVal, "监听到了旧值"+oldVal);
            }
        }
    })
</script>

Monitoring via vm.$watch:

<div>
    <h2 id="今天天气很-info">今天天气很{{info}}</h2>
    <button>切换天气</button>
</div>
<script></script>
<script>
    const vm = new Vue({
        el:&#39;#root&#39;,
        data:{
            isHot:true
        },
        computed:{
            info(){
                return this.isHot ? &#39;炎热&#39; : &#39;凉爽&#39;
            }
        },
        methods:{
            changeWeather(){
                this.isHot = !this.isHot
            }
        },
    })
    vm.$watch(&#39;info&#39;,{
        handler(newVal,oldVal){
            console.log(&#39;天气被修改了&#39;, newVal, oldVal);
        }
    })
</script>

##immediate option

by default , the component will not call the watch listener after the initial loading. If you want the watch listener to be called immediately, you need to use the immediate option. The function of immediate is to control whether the listener

is automatically triggered once. , the default value of the option is: false

<div>
    <input>
</div>
<script></script>
<script>
    const vm = new Vue({
        el:&#39;#root&#39;,
        data:{
            name:&#39;admin&#39;
        },
        watch:{
            //定义对象格式的侦听器
            name:{
                handler(newVal,oldVal){
                    console.log(newVal, oldVal);
                },
                immediate:true
            }
        }
    })
</script>

Deep monitoring

If the watch is listening An object cannot be monitored if the property value in the object changes. At this time, you need to use the deep option to enable deep monitoring. As long as any attribute in the object changes, the "object listener" will be triggered.

<div>
    <input>
</div>
<script></script>
<script>
    const vm = new Vue({
        el:&#39;#root&#39;,
        data:{
            info:{
                name:&#39;admin&#39;
            }
        },
        watch:{
            info: {
                handler(newVal){
                    console.log(newVal);
                },
                //开启深度监听
                deep:true
            }
        }
    })
</script>

If the object you want to listen to is the change of a sub-property, it must be wrapped in single quotes.

watch:{
    "info.name"(newVal){
        console.log(newVal);
    }
}

Summary:

1) The watch in Vue does not monitor changes in the internal value of the object by default (one layer )

2) Configure deep:true to monitor changes in the internal value of the object (multi-layer)

3) Vue itself can monitor changes in the internal value of the object, but the watch provided by Vue cannot by default

4) When using watch, decide whether to use in-depth monitoring based on the specific structure of the data

watch can start asynchronous tasks, the case is as follows:

<div>
    <input><br>
    <input><br>
    全名:<span>{{fullname}}</span>
</div>
<script></script>
<script>
    const vm = new Vue({
        el:"#root",
        data:{
            firstname:&#39;张&#39;,
            lastname:&#39;三&#39;,
            fullname:&#39;张-三&#39;
        },
        //watch能开启异步任务
        watch:{
            firstname(val){
                setTimeout(()=>{
                    this.fullname = val + &#39;-&#39; + this.lastname
                },1000)
            },
            lastname(val){
                this.fullname = this.firstname+&#39;-&#39;+val
            }
        }
    })
</script>

The difference between computed and watch:

1.Watch can complete all the functions that computed can complete.

2. The functions that watch can complete may not be completed by computed. For example: watch can perform asynchronous operations.

Implicit principles:

1. Functions managed by Vue are best written as ordinary functions, so that this points to the vm or component instance object

2. Functions that are not managed by Vue (timer callback function, ajax callback function, Promise callback function) are best written as arrow functions, so that this points to the vm or component instance object.

[Related recommendations: JavaScript video tutorial, web front-end development]

The above is the detailed content of The use of JavaScript computed properties and monitoring (listening) properties. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.