Vue--"Use of calculated properties and monitoring (listening) properties

Table of contents

Computed property (computed)

Monitor property (watch)

Two Methods of Surveillance

immediate option

deep monitoring


Computed property (computed)

A computed property refers to a value that is finally obtained after a series of operations . This dynamically calculated attribute value can be used by the template structure or the methods method, as follows:

<div id="root">
    R:<input type="text" v-model.number="r"><br>
    G:<input type="text" v-model.number="g"><br>
    B:<input type="text" v-model.number="b">
    <div class="box" :style="{backgroundColor:rgb}">
        {
   
   {rgb}}
    </div>
    <button @click="show">按钮</button>
</div>
<script src="/vue/vue.js"></script>
<script>
    const vm = new Vue({
        el:'#root',
        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>

Example of using a dynamic name change to implement a computed property:

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

Computed property :

1. Definition: The attribute to be used does not exist, and it must be obtained through the existing attribute

2. Principle: The bottom layer uses the getter and setter provided by the Object.defineproperty method

3. Advantages: Compared with the implementation of methods, there is an internal cache mechanism (multiplexing), which is more efficient and easy to debug

4. Remarks: The computed attribute will eventually appear on the vm, and it can be read and used directly; if the computed attribute is to be modified, the set function must be written to respond to the change, and the data in the set to cause the calculation depends on changes.

Monitor property (watch)

The watch monitor (listener) allows developers to monitor data changes, so as to perform specific operations on data changes.

Two Methods of Surveillance

Pass in the watch configuration when passing new Vue :

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

Monitoring via vm.$watch :

<div id="root">
    <h2>今天天气很{
   
   {info}}</h2>
    <button @click="changeWeather">切换天气</button>
</div>
<script src="./vue.js"></script>
<script>
    const vm = new Vue({
        el:'#root',
        data:{
            isHot:true
        },
        computed:{
            info(){
                return this.isHot ? '炎热' : '凉爽'
            }
        },
        methods:{
            changeWeather(){
                this.isHot = !this.isHot
            }
        },
    })
    vm.$watch('info',{
        handler(newVal,oldVal){
            console.log('天气被修改了', 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 role of immediate is to control whether the listener is automatically triggered once. The option Default value: false

<div id="root">
    <input type="text" v-model="name">
</div>
<script src="./vue.js"></script>
<script>
    const vm = new Vue({
        el:'#root',
        data:{
            name:'admin'
        },
        watch:{
            //定义对象格式的侦听器
            name:{
                handler(newVal,oldVal){
                    console.log(newVal, oldVal);
                },
                immediate:true
            }
        }
    })
</script>

deep monitoring

If the watch listens to an object, if the property value in the object changes, it cannot be monitored. 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 id="root">
    <input type="text" v-model="info.name">
</div>
<script src="./vue.js"></script>
<script>
    const vm = new Vue({
        el:'#root',
        data:{
            info:{
                name:'admin'
            }
        },
        watch:{
            info: {
                handler(newVal){
                    console.log(newVal);
                },
                //开启深度监听
                deep:true
            }
        }
    })
</script>

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

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

Summary :

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

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

3) Vue itself can monitor the change of 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 according to the specific structure of the data

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

<div id="root">
    <input type="text" v-model="firstname"><br>
    <input type="text" v-model="lastname"><br>
    全名:<span>{
   
   {fullname}}</span>
</div>
<script src="/vue/vue.js"></script>
<script>
    const vm = new Vue({
        el:"#root",
        data:{
            firstname:'张',
            lastname:'三',
            fullname:'张-三'
        },
        //watch能开启异步任务
        watch:{
            firstname(val){
                setTimeout(()=>{
                    this.fullname = val + '-' + this.lastname
                },1000)
            },
            lastname(val){
                this.fullname = this.firstname+'-'+val
            }
        }
    })
</script>

The difference between computed and watch :

1. The functions that can be completed by computed can be completed by watch.

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

Implicit principle :

1. The functions managed by Vue are best written as ordinary functions, so that the point of this is the vm or component instance object

2. For functions not managed by Vue (timer callback function, ajax callback function, Promise callback function), it is best to write an arrow function, so that the point of this is the vm or component instance object.

Guess you like

Origin blog.csdn.net/qq_53123067/article/details/127667787