Home >Web Front-end >Vue.js >Vue computed properties and listeners and filters super detailed introduction

Vue computed properties and listeners and filters super detailed introduction

WBOY
WBOYforward
2022-10-08 16:38:451670browse

This article brings you relevant knowledge about vue, which mainly introduces detailed introduction to calculated properties, listeners and filters, including the total use of calculated properties in the shopping cart, etc. Let’s take a look at the content below. I hope it will be helpful to everyone.

【Related recommendations: javascript video tutorial, vue.js tutorial

1 . Calculated properties

1.1 Usage

Overview:

Putting too much logic in a template will make the template overweight and difficult to Maintenance, using calculated properties can make templates concise and easy to maintain. Computed properties are cached based on their responsive dependencies. Computed properties are more suitable for processing multiple variables or objects and returning a result value. That is, if one of the values ​​of multiple variables changes, the value we monitor will be The value will also change.

Computed properties are defined in the Vue object. Functions are defined in the keyword computed property object and return a value. When using calculated properties, they are used in the same way as the data in data.

Usage:

When we do not use calculated properties, we want to calculate the results in the template, and there are several ways to write them:

<p id="app">
    <!-- 方法1:vue在使用时,不推荐在模板中来写过多的逻辑 -->
    <h3>{{ n1+n2 }}</h3>
    <!-- 方法2:对于一个计算结果,可能在当前的页面中,显示多个,显示几次就调用这个函数几次,性能会降低 -->
    <h3>{{ sum() }}</h3>
    <h3>{{ sum() }}</h3>
    <h3>{{ sum() }}</h3>
</p>
<script>
    const vm = new Vue({
        el: &#39;#app&#39;,
        data: {
            n1: 1,
            n2: 2
        },
        methods: {
            sum() {
                console.log(&#39;sum --- methods&#39;);
                return this.n1 + this.n2
            }
        }
    })
</script>

Vue computed properties and listeners and filters super detailed introduction

If you want to calculate a result, you can use vue to provide calculated properties, and the calculated properties also have a caching function. If your dependencies have not changed, it will read the data in the cache when it is called again.

<p id="app">
    <p>{{total}}</p>
    <p>{{total}}</p>
    <p>{{total}}</p>
</p>
<script>
    const vm = new Vue({
        el: &#39;#app&#39;,
        data: {
            n1: 1,
            n2: 2
        },
        // 计算[属性]
        computed: {
            // 调用时,直接写名称就可以,不用写小括号
            // 计算属性中的依赖项,可以是一个,也是可以N个,取决于你在计算属性中调用多少
            // 注:此方法中不能写异步
            // 简写 使用最多的写法
            total() {
                console.log(&#39;computed -- total&#39;)
                // 在计算属性中,调用了 n1和n2,则n1和n2就是它的依赖项,如果这两个依赖项,有一个发生改变,则它会重新计算,如果两个都没有发生改变,则第2之后调用,读取缓存中的数据
                return this.n1 + this.n2
            }
        },
        methods: {
            // 计算属性中的方法在 methods 中也可以调用
            sum() {
                console.log(&#39;sum --- methods&#39;, this.total);
                return this.n1 + this.n2
            }
        }
    })
</script>

Vue computed properties and listeners and filters super detailed introduction

Note:

  • When calling a calculated attribute, just write the name directly in the template without parentheses.
  • In the calculated attribute, n1 and n2 are called, then n1 and n2 are its dependencies. If one of these two dependencies changes, it will be recalculated. If neither of them exists, If a change occurs, it will be called after the second call to read the data in the cache. This is why the above calculation is performed three times, but the calculation method is only called once, because the dependencies in the calculated attribute have not changed.
  • The dependency in the calculated property can be one or N, depending on how many you call in the calculated property.
  • Asynchronous cannot be written in the method in the calculated attribute.
  • The calculated properties above are abbreviations. Abbreviation is the most commonly used method.
  • Computed properties can be called not only in templates, but also in methods.

If the defined calculated property is abbreviated, an error will be reported when assigning a value to the calculated property. Only when written in a standard way, it can perform assignment operations on calculated properties. Let's take a look at what the standard writing method is.

<p id="app">
    <h3>{{ sum() }}</h3>
    <h3>{{msg}}</h3>
</p>
<script>
    const vm = new Vue({
        el: &#39;#app&#39;,
        data: {
            n1: 1,
            n2: 2,
            msg: &#39;&#39;
        },
        // 计算[属性]
        computed: {
            // 标准写法
            total: {
                // 简写只是实现的了标准写法中的get方法
                get() {
                    return this.n1 + this.n2
                },
                set(newVal) {
                    if (newVal > 10) {
                        this.msg = &#39;值有点的大&#39;
                    }
                }
            }
        },
        methods: {
            sum() {
                // 赋值只会触发标准方式中的set方法,然后你可以得到它,完成一些别的工作
                if (this.total > 6) {
                    this.total = 101
                }
                return this.n1 + this.n2
            }
        }
    })
</script>

Vue computed properties and listeners and filters super detailed introduction

Note:

  • The abbreviation method only implements the get method in the standard writing method.
  • Assignment will only trigger the set method in the standard way, and then you can get the new value and complete some other work.

1.2 Case - Shopping Cart Total Using Calculated Property

<!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>vue学习使用</title>
        <!-- 第1步: 引入vue库文件 -->
        <script src="./js/vue.js"></script>
    </head>
    <body>
        <!-- 第2步:挂载点 -->
        <p id="app">
            <table border="1" width="600">
                <tr>
                    <th>序号</th>
                    <th>名称</th>
                    <th>单价</th>
                    <th>数量</th>
                    <th>操作</th>
                </tr>
                <tr v-for="item,index in carts">
                    <td>{{index+1}}</td>
                    <td>{{item.name}}</td>
                    <td>{{item.price}}</td>
                    <td>
                        <button @click="setNum(1,index)">+++</button>
                        <input type="number" v-model="item.num">
                        <button @click="setNum(-1,index)">---</button>
                    </td>
                    <td>
                        <button @click="del(index)">删除</button>
                    </td>
                </tr>
            </table>
            <hr>
            <h3>
                合计:
                {{totalPrice}}
            </h3>
        </p>
        <!-- 第3步:实例化vue -->
        <script>
            const vm = new Vue({
                el: &#39;#app&#39;,
                data: {
                    carts: [
                        { id: 1, name: &#39;小米12pro&#39;, price: 1, num: 1 },
                        { id: 2, name: &#39;华为手机&#39;, price: 2, num: 1 },
                        { id: 3, name: &#39;水果手机&#39;, price: 3, num: 1 },
                    ]
                },
                methods: {
                    setNum(n, index) {
                        this.carts[index].num += n
                        this.carts[index].num = Math.min(3, Math.max(1, this.carts[index].num))
                    },
                    del(index) {
                        confirm(&#39;确定删除&#39;) && this.carts.splice(index, 1)
                    }
                },
                // 计算属性
                computed: {
                    totalPrice() {
                        return this.carts.reduce((prev, { price, num }) => {
                            // 依赖项
                            prev += price * num
                            return prev
                        }, 0)
                    }
                }
            })
        </script>
    </body>
</html>

Vue computed properties and listeners and filters super detailed introduction

2. Listener

Overview:

Use watch to listen for changes in data in data. The attributes in watch must be data that already exists in data.

When you need to monitor changes in an object, the ordinary watch method cannot monitor the changes in the internal properties of the object. Only the data in data can monitor the changes. At this time, you need the deep attribute to monitor the object in depth. .

Usage:

Standard writing:

<p id="app">
    <p>
        <input type="text" v-model="username">
        <span>{{errorUsername}}</span>
    </p>
</p>
<script>
    const vm = new Vue({
        el: &#39;#app&#39;,
        data: {
            username: &#39;&#39;,
            errorUsername: &#39;&#39;
        },
        // 监听器,它用来监听data配置中的数据的变化,一但有变化,就会自动触发.默认情况下,初始化不触发
        // 在监听器中是可以得到this对象的
        // 监听器它的依赖项,只有一个,一对一
        // 监听器中可以写异步
        watch: {
            // 方法名或属性名 就是你要观察的data中的属性名称
            // 标准写法
            username: {
                // newValue 变化后的值;oldValue 变化前的值
                handler(newValue, oldValue) {
                    if (newValue.length >= 3) this.errorUsername = &#39;账号过长&#39;
                    else this.errorUsername = &#39;&#39;
                }
            }
        })
</script>

Vue computed properties and listeners and filters super detailed introduction

Note:

  1. The listener is used to monitor data configuration Once the data in the data changes, it will be automatically triggered. By default, initialization is not triggered.
  2. This object can be obtained in the listener.
  3. The listener has only one dependency, one-to-one.
  4. Asynchronous (Ajax or setTimeout) can be written in the listener.

Abbreviation:

<p id="app">
    <p>
        <input type="text" v-model="username">
        <span>{{errorUsername}}</span>
    </p>
</p>
<script>
    const vm = new Vue({
        el: &#39;#app&#39;,
        data: {
            username: &#39;&#39;,
            errorUsername: &#39;&#39;
        },
        watch: {
            username(newValue, oldValue) {
                if (newValue.length >= 3) this.errorUsername = &#39;账号过长&#39;
                else this.errorUsername = &#39;&#39;
            }
        }
    })
</script>

Vue computed properties and listeners and filters super detailed introduction

When initializing, enable the listener writing method:

<p id="app">
    <p>
        <input type="text" v-model="username">
        <span>{{errorUsername}}</span>
    </p>
</p>
<script>
    const vm = new Vue({
        el: &#39;#app&#39;,
        data: {
            username: &#39;aaa&#39;,
            errorUsername: &#39;&#39;
        },
        watch: {
            // 方法名或属性名 就是你要观察的data中的属性名称
            // 标准写法
            username: {
                handler(newValue, oldValue) {
                    if (newValue.length >= 3) this.errorUsername = &#39;账号过长&#39;
                    else this.errorUsername = &#39;&#39;
                },
                // 初始时,执行1次 --- 一般情况下,不启用  只有在标准写法下面,才有此配置
                immediate: true
            }
        })
</script>

Vue computed properties and listeners and filters super detailed introduction

注意:这个配置只有在标准写法下才能有。

监听对象中的属性变化:

<p id="app">
    <p>
        <input type="number" v-model.number="user.id"> 
    </p>
</p>
<script>
    const vm = new Vue({
        el: &#39;#app&#39;,
        data: {
            user: { id: 100, name: &#39;aaa&#39; }
        },
        // 监听对象中的指定的属性数据的变化  推荐如果你监听的是一个对象中数据变化,建议这样的方式
        watch: {
            &#39;user.id&#39;(newValue, oldValue){
                console.log(newValue, oldValue);
            }
        }
    })
</script>

Vue computed properties and listeners and filters super detailed introduction

监听对象变化:

<p id="app">
    <p>
        <input type="number" v-model.number="user.id"> 
    </p>
</p>
<script>
    const vm = new Vue({
        el: &#39;#app&#39;,
        data: {
            user: { id: 100, name: &#39;aaa&#39; }
        },
        watch: {
            // 监听对象,只能使用标准方式来写
            // 监听对象变化,它的前后值是一样的,无法区分
            user: {
                // 深度监听
                deep: true,
                handler(newValue, oldValue) {
                    console.log(newValue, oldValue);
                },
            }
        }
    })
</script>

Vue computed properties and listeners and filters super detailed introduction

注意:

  1. 监听对象,只能使用标准方式来写
  2. 监听对象变化,它的前后值是一样的,无法区分

3. 过滤器

概述:

在数据被渲染之前,可以对其进行进一步处理,比如将字符截取或者将小写统一转换为大写等等,过滤器本身就是一个方法。

过滤器的作用就是为了对于界面中显示的数据进行处理操作。

过滤器可以定义全局或局部。

定义全局过滤器:

<p id="app">
    <h3>{{ phone | phoneCrypt }}</h3>
</p>
<script>
    // 参数1:过滤器的名称,可以随意起名
    // 参数2:回调函数,回调函数中的参数最少要有一个,第1位参数,永远指向为要过滤的数据
    Vue.filter(&#39;phoneCrypt&#39;, value => {
        return value.slice(0, 3) + &#39;~~~~&#39; + value.slice(7)
    })
    const vm = new Vue({
        el: &#39;#app&#39;,
        data: {
            phone: &#39;13523235235&#39;
        }
    })
</script>

Vue computed properties and listeners and filters super detailed introduction

上面的全局过滤器的回调函数中只有一个参数,我们还可以定义多个参数:

<p id="app">
    <!-- 这里传的第一个参数,对应全局过滤器的回调函数中定义的第二个参数 -->
    <h3>{{ phone | phoneCrypt(&#39;!!!!&#39;) }}</h3>
</p>
<script>
    Vue.filter(&#39;phoneCrypt&#39;, (value, salt = &#39;****&#39;) => {
        return value.slice(0, 3) + salt + value.slice(7)
    })
    const vm = new Vue({
        el: &#39;#app&#39;,
        data: {
            phone: &#39;13523235235&#39;
        }
    })
</script>

Vue computed properties and listeners and filters super detailed introduction

定义局部过滤器:

<p id="app">
    <h3>{{ phone | phoneCrypt(&#39;!!!!&#39;) }}</h3>
</p>
<script>
    const vm = new Vue({
        el: &#39;#app&#39;,
        data: {
            phone: &#39;13523235235&#39;
        },
        // 局部过滤器
        filters:{
            phoneCrypt(value, salt = &#39;****&#39;){
                return value.slice(0, 3) + salt + value.slice(7)
            }
        }
    })
</script>

Vue computed properties and listeners and filters super detailed introduction

【相关推荐:javascript视频教程vue.js教程

The above is the detailed content of Vue computed properties and listeners and filters super detailed introduction. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:jb51.net. If there is any infringement, please contact admin@php.cn delete