search
HomeWeb Front-endVue.jsVue computed properties and listeners and filters super detailed introduction

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 id="nbsp-n-n-nbsp">{{ n1+n2 }}</h3>
    <!-- 方法2:对于一个计算结果,可能在当前的页面中,显示多个,显示几次就调用这个函数几次,性能会降低 -->
    <h3 id="nbsp-sum-nbsp">{{ sum() }}</h3>
    <h3 id="nbsp-sum-nbsp">{{ sum() }}</h3>
    <h3 id="nbsp-sum-nbsp">{{ 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 id="nbsp-sum-nbsp">{{ sum() }}</h3>
    <h3 id="msg">{{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 id="nbsp-phone-nbsp-nbsp-phoneCrypt-nbsp">{{ 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 id="nbsp-phone-nbsp-nbsp-phoneCrypt-nbsp">{{ 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 id="nbsp-phone-nbsp-nbsp-phoneCrypt-nbsp">{{ 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:脚本之家. If there is any infringement, please contact admin@php.cn delete
What are the disadvantages of VueJs?What are the disadvantages of VueJs?May 05, 2025 am 12:06 AM

The main disadvantages of Vue.js include: 1. The ecosystem is relatively new, and third-party libraries and tools are not as rich as other frameworks; 2. The learning curve becomes steep in complex functions; 3. Community support and resources are not as extensive as React and Angular; 4. Performance problems may be encountered in large applications; 5. Version upgrades and compatibility challenges are greater.

Netflix: Unveiling Its Frontend FrameworksNetflix: Unveiling Its Frontend FrameworksMay 04, 2025 am 12:16 AM

Netflix uses React as its front-end framework. 1.React's component development and virtual DOM mechanism improve performance and development efficiency. 2. Use Webpack and Babel to optimize code construction and deployment. 3. Use code segmentation, server-side rendering and caching strategies for performance optimization.

Frontend Development with Vue.js: Advantages and TechniquesFrontend Development with Vue.js: Advantages and TechniquesMay 03, 2025 am 12:02 AM

Reasons for Vue.js' popularity include simplicity and easy learning, flexibility and high performance. 1) Its progressive framework design is suitable for beginners to learn step by step. 2) Component-based development improves code maintainability and team collaboration efficiency. 3) Responsive systems and virtual DOM improve rendering performance.

Vue.js vs. React: Ease of Use and Learning CurveVue.js vs. React: Ease of Use and Learning CurveMay 02, 2025 am 12:13 AM

Vue.js is easier to use and has a smooth learning curve, which is suitable for beginners; React has a steeper learning curve, but has strong flexibility, which is suitable for experienced developers. 1.Vue.js is easy to get started with through simple data binding and progressive design. 2.React requires understanding of virtual DOM and JSX, but provides higher flexibility and performance advantages.

Vue.js vs. React: Which Framework is Right for You?Vue.js vs. React: Which Framework is Right for You?May 01, 2025 am 12:21 AM

Vue.js is suitable for fast development and small projects, while React is more suitable for large and complex projects. 1.Vue.js is simple and easy to learn, suitable for rapid development and small projects. 2.React is powerful and suitable for large and complex projects. 3. The progressive features of Vue.js are suitable for gradually introducing functions. 4. React's componentized and virtual DOM performs well when dealing with complex UI and data-intensive applications.

Vue.js vs. React: A Comparative Analysis of JavaScript FrameworksVue.js vs. React: A Comparative Analysis of JavaScript FrameworksApr 30, 2025 am 12:10 AM

Vue.js and React each have their own advantages and disadvantages. When choosing, you need to comprehensively consider team skills, project size and performance requirements. 1) Vue.js is suitable for fast development and small projects, with a low learning curve, but deep nested objects can cause performance problems. 2) React is suitable for large and complex applications, with a rich ecosystem, but frequent updates may lead to performance bottlenecks.

Vue.js vs. React: Use Cases and ApplicationsVue.js vs. React: Use Cases and ApplicationsApr 29, 2025 am 12:36 AM

Vue.js is suitable for small to medium-sized projects, while React is suitable for large projects and complex application scenarios. 1) Vue.js is easy to use and is suitable for rapid prototyping and small applications. 2) React has more advantages in handling complex state management and performance optimization, and is suitable for large projects.

Vue.js vs. React: Comparing Performance and EfficiencyVue.js vs. React: Comparing Performance and EfficiencyApr 28, 2025 am 12:12 AM

Vue.js and React each have their own advantages: Vue.js is suitable for small applications and rapid development, while React is suitable for large applications and complex state management. 1.Vue.js realizes automatic update through a responsive system, suitable for small applications. 2.React uses virtual DOM and diff algorithms, which are suitable for large and complex applications. When selecting a framework, you need to consider project requirements and team technology stack.

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools