


Vue 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: '#app', data: { n1: 1, n2: 2 }, methods: { sum() { console.log('sum --- methods'); return this.n1 + this.n2 } } }) </script>
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: '#app', data: { n1: 1, n2: 2 }, // 计算[属性] computed: { // 调用时,直接写名称就可以,不用写小括号 // 计算属性中的依赖项,可以是一个,也是可以N个,取决于你在计算属性中调用多少 // 注:此方法中不能写异步 // 简写 使用最多的写法 total() { console.log('computed -- total') // 在计算属性中,调用了 n1和n2,则n1和n2就是它的依赖项,如果这两个依赖项,有一个发生改变,则它会重新计算,如果两个都没有发生改变,则第2之后调用,读取缓存中的数据 return this.n1 + this.n2 } }, methods: { // 计算属性中的方法在 methods 中也可以调用 sum() { console.log('sum --- methods', this.total); return this.n1 + this.n2 } } }) </script>
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: '#app', data: { n1: 1, n2: 2, msg: '' }, // 计算[属性] computed: { // 标准写法 total: { // 简写只是实现的了标准写法中的get方法 get() { return this.n1 + this.n2 }, set(newVal) { if (newVal > 10) { this.msg = '值有点的大' } } } }, methods: { sum() { // 赋值只会触发标准方式中的set方法,然后你可以得到它,完成一些别的工作 if (this.total > 6) { this.total = 101 } return this.n1 + this.n2 } } }) </script>
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: '#app', data: { carts: [ { id: 1, name: '小米12pro', price: 1, num: 1 }, { id: 2, name: '华为手机', price: 2, num: 1 }, { id: 3, name: '水果手机', 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('确定删除') && this.carts.splice(index, 1) } }, // 计算属性 computed: { totalPrice() { return this.carts.reduce((prev, { price, num }) => { // 依赖项 prev += price * num return prev }, 0) } } }) </script> </body> </html>
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: '#app', data: { username: '', errorUsername: '' }, // 监听器,它用来监听data配置中的数据的变化,一但有变化,就会自动触发.默认情况下,初始化不触发 // 在监听器中是可以得到this对象的 // 监听器它的依赖项,只有一个,一对一 // 监听器中可以写异步 watch: { // 方法名或属性名 就是你要观察的data中的属性名称 // 标准写法 username: { // newValue 变化后的值;oldValue 变化前的值 handler(newValue, oldValue) { if (newValue.length >= 3) this.errorUsername = '账号过长' else this.errorUsername = '' } } }) </script>
Note:
- 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.
- This object can be obtained in the listener.
- The listener has only one dependency, one-to-one.
- 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: '#app', data: { username: '', errorUsername: '' }, watch: { username(newValue, oldValue) { if (newValue.length >= 3) this.errorUsername = '账号过长' else this.errorUsername = '' } } }) </script>
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: '#app', data: { username: 'aaa', errorUsername: '' }, watch: { // 方法名或属性名 就是你要观察的data中的属性名称 // 标准写法 username: { handler(newValue, oldValue) { if (newValue.length >= 3) this.errorUsername = '账号过长' else this.errorUsername = '' }, // 初始时,执行1次 --- 一般情况下,不启用 只有在标准写法下面,才有此配置 immediate: true } }) </script>
注意:这个配置只有在标准写法下才能有。
监听对象中的属性变化:
<p id="app"> <p> <input type="number" v-model.number="user.id"> </p> </p> <script> const vm = new Vue({ el: '#app', data: { user: { id: 100, name: 'aaa' } }, // 监听对象中的指定的属性数据的变化 推荐如果你监听的是一个对象中数据变化,建议这样的方式 watch: { 'user.id'(newValue, oldValue){ console.log(newValue, oldValue); } } }) </script>
监听对象变化:
<p id="app"> <p> <input type="number" v-model.number="user.id"> </p> </p> <script> const vm = new Vue({ el: '#app', data: { user: { id: 100, name: 'aaa' } }, watch: { // 监听对象,只能使用标准方式来写 // 监听对象变化,它的前后值是一样的,无法区分 user: { // 深度监听 deep: true, handler(newValue, oldValue) { console.log(newValue, oldValue); }, } } }) </script>
注意:
- 监听对象,只能使用标准方式来写
- 监听对象变化,它的前后值是一样的,无法区分
3. 过滤器
概述:
在数据被渲染之前,可以对其进行进一步处理,比如将字符截取或者将小写统一转换为大写等等,过滤器本身就是一个方法。
过滤器的作用就是为了对于界面中显示的数据进行处理操作。
过滤器可以定义全局或局部。
定义全局过滤器:
<p id="app"> <h3 id="nbsp-phone-nbsp-nbsp-phoneCrypt-nbsp">{{ phone | phoneCrypt }}</h3> </p> <script> // 参数1:过滤器的名称,可以随意起名 // 参数2:回调函数,回调函数中的参数最少要有一个,第1位参数,永远指向为要过滤的数据 Vue.filter('phoneCrypt', value => { return value.slice(0, 3) + '~~~~' + value.slice(7) }) const vm = new Vue({ el: '#app', data: { phone: '13523235235' } }) </script>
上面的全局过滤器的回调函数中只有一个参数,我们还可以定义多个参数:
<p id="app"> <!-- 这里传的第一个参数,对应全局过滤器的回调函数中定义的第二个参数 --> <h3 id="nbsp-phone-nbsp-nbsp-phoneCrypt-nbsp">{{ phone | phoneCrypt('!!!!') }}</h3> </p> <script> Vue.filter('phoneCrypt', (value, salt = '****') => { return value.slice(0, 3) + salt + value.slice(7) }) const vm = new Vue({ el: '#app', data: { phone: '13523235235' } }) </script>
定义局部过滤器:
<p id="app"> <h3 id="nbsp-phone-nbsp-nbsp-phoneCrypt-nbsp">{{ phone | phoneCrypt('!!!!') }}</h3> </p> <script> const vm = new Vue({ el: '#app', data: { phone: '13523235235' }, // 局部过滤器 filters:{ phoneCrypt(value, salt = '****'){ return value.slice(0, 3) + salt + value.slice(7) } } }) </script>
【相关推荐: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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



There are three ways to refer to JS files in Vue.js: directly specify the path using the <script> tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

In Vue.js, lazy loading allows components or resources to be loaded dynamically as needed, reducing initial page loading time and improving performance. The specific implementation method includes using <keep-alive> and <component is> components. It should be noted that lazy loading can cause FOUC (splash screen) issues and should be used only for components that need lazy loading to avoid unnecessary performance overhead.

You can query the Vue version by using Vue Devtools to view the Vue tab in the browser's console. Use npm to run the "npm list -g vue" command. Find the Vue item in the "dependencies" object of the package.json file. For Vue CLI projects, run the "vue --version" command. Check the version information in the <script> tag in the HTML file that refers to the Vue file.

Implement marquee/text scrolling effects in Vue, using CSS animations or third-party libraries. This article introduces how to use CSS animation: create scroll text and wrap text with <div>. Define CSS animations and set overflow: hidden, width, and animation. Define keyframes, set transform: translateX() at the beginning and end of the animation. Adjust animation properties such as duration, scroll speed, and direction.

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses <router-link to="/" component window.history.back(), and the method selection depends on the scene.
