Home Web Front-end JS Tutorial Computed properties and listener use cases for VUE

Computed properties and listener use cases for VUE

Mar 10, 2018 am 10:41 AM
use Case

This time I will bring you the use cases of VUE's computed properties and listeners. What are the precautions for using VUE's computed properties and listeners? The following is a practical case, let's take a look.

Written at the front

The use of vue in the previous article talked about vue

life cycle, vue instances, and template syntax. This time we talk about vue’s calculated properties and listeners

Computed properties

Expressionsin the template in vue are very convenient, but the original intention of designing them is Used for simple operations. Putting too much logic into a template can make it overweight and difficult to maintain. For example:

<div id="example">
  {{ message.split(&#39;&#39;).reverse().join(&#39;&#39;) }}
</div>
Copy after login

Here, the template is no longer simple declarative logic. You have to look at it for a while to realize what this string of code is doing, and it becomes even more difficult to handle when you want to reference it multiple times in the template.

So, for any complex logic, you should use computed properties.

For example

<div id="example">
  <p>Original message: "{{ message }}"</p>
  <p>Computed reversed message: "{{ reversedMessage }}"</p>
</div>
var vm = new Vue({
  el: &#39;#example&#39;,
  data: {
    message: &#39;Hello&#39;
  },
  computed: {
    // 计算属性的 getter
    reversedMessage: function () {
      // `this` 指向 vm 实例      return this.message.split(&#39;&#39;).reverse().join(&#39;&#39;)
    }
  }
})
Original message: "Hello"
Computed reversed message: "olleH"
Copy after login

A calculated property reversedMessage is declared here. The function provided by vue will be used as the getter function of the property vm.reversedMessage:

console.log(vm.reversedMessage) // => 'olleH'vm.message = 'Goodbye'console.log(vm. reversedMessage) // => 'eybdooG'


You can bind computed properties in templates just like normal properties. Vue knows that vm.reversedMessage depends on vm.message, so when vm.message changes, all bindings that depend on vm.reversedMessage are also updated. And the best part is that Vue has created this dependency in a declarative way: the getter function of the calculated property has no side effects, which makes it easier to test and understand.

Computed property cache vs method

You may have noticed that vue can achieve the same effect by calling a method in an expression:

<p>Reversed message: "{{ reversedMessage() }}"</p>
// 在组件中
methods: {
  reversedMessage: function () {    return this.message.split(&#39;&#39;).reverse().join(&#39;&#39;)
  }
}
Copy after login

vue can define the same function As a method rather than a computed property. The end result is indeed exactly the same both ways. However, the difference is that computed properties are cached based on their dependencies. A computed property is only re-evaluated when its associated dependencies change. This means that as long as the message has not changed, multiple accesses to the reversedMessage calculated property will immediately return the previous calculated result without having to execute the function again.

This also means that the following computed properties will no longer be updated, because Date.now() is not a reactive dependency:

computed: {
  now: function () {    return Date.now()
  }
}
Copy after login

In contrast, whenever a re-render is triggered, the calling method will The function will always be executed again.

Why do we need caching? Suppose we have a computationally expensive property A, which requires traversing a huge array and doing a lot of calculations. Then we might have other computed properties that depend on A . Without caching, we would inevitably execute A's getter multiple times! If you don't want caching, use methods instead.

Computed properties vs listening properties

Vue provides a more general way to observe and respond to data changes on Vue instances: listening properties. When you have some data that needs to change when other data changes, it's easy to abuse watches - especially if you've used

AngularJS before. However, it is often better to use computed properties rather than imperative watch callbacks. Consider this example:

<div id="demo">{{ fullName }}</div>
var vm = new Vue({
  el: &#39;#demo&#39;,
  data: {
    firstName: &#39;Foo&#39;,
    lastName: &#39;Bar&#39;,
    fullName: &#39;Foo Bar&#39;
  },
  watch: {
    firstName: function (val) {
      this.fullName = val + &#39; &#39; + this.lastName
    },
    lastName: function (val) {
      this.fullName = this.firstName + &#39; &#39; + val
    }
  }
})
Copy after login

The above code is imperative and repetitive. Compare this to the computed property version:

var vm = new Vue({
  el: &#39;#demo&#39;,
  data: {
    firstName: &#39;Foo&#39;,
    lastName: &#39;Bar&#39;
  },
  computed: {
    fullName: function () {      return this.firstName + &#39; &#39; + this.lastName
    }
  }
})
Copy after login

Computed property setters

Computed properties have only getters by default, but you can also provide a setter if needed:

// ...
computed: {
  fullName: {
    // getter
    get: function () {      return this.firstName + &#39; &#39; + this.lastName
    },
    // setter
    set: function (newValue) {
      var names = newValue.split(&#39; &#39;)
      this.firstName = names[0]
      this.lastName = names[names.length - 1]
    }
  }
}
// ...
Copy after login

Now when running vm.fullName = 'John Doe', the setter will be called, and vm.firstName and vm.lastName will be updated accordingly.

Listener

While computed properties are more appropriate in most cases, sometimes a custom listener is needed. This is why Vue provides a more general way to respond to changes in data through the watch option. This approach is most useful when you need to perform asynchronous or expensive operations when data changes.

Example:

<div id="watch-example">
  <p>
    Ask a yes/no question:
    <input v-model="question">
  </p>
  <p>{{ answer }}</p>
</div>
<!-- 因为 AJAX 库和通用工具的生态已经相当丰富,Vue 核心代码没有重复 -->
<!-- 提供这些功能以保持精简。这也可以让你自由选择自己更熟悉的工具。 -->
<script src="https://cdn.jsdelivr.net/npm/axios@0.12.0/dist/axios.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/lodash@4.13.1/lodash.min.js"></script>
<script>
var watchExampleVM = new Vue({
  el: &#39;#watch-example&#39;,
  data: {
    question: &#39;&#39;,
    answer: &#39;I cannot give you an answer until you ask a question!&#39;
  },
  watch: {
    // 如果 `question` 发生改变,这个函数就会运行
    question: function (newQuestion, oldQuestion) {
      this.answer = &#39;Waiting for you to stop typing...&#39;
      this.getAnswer()
    }
  },
  methods: {
    // `_.debounce` 是一个通过 Lodash 限制操作频率的函数。
    // 在这个例子中,我们希望限制访问 yesno.wtf/api 的频率
    // AJAX 请求直到用户输入完毕才会发出。想要了解更多关于
    // `_.debounce` 函数 (及其近亲 `_.throttle`) 的知识,
    // 请参考:https://lodash.com/docs#debounce
    getAnswer: _.debounce(
      function () {        if (this.question.indexOf(&#39;?&#39;) === -1) {
          this.answer = &#39;Questions usually contain a question mark. ;-)&#39;
          return
        }
        this.answer = &#39;Thinking...&#39;
        var vm = this
        axios.get(&#39;https://yesno.wtf/api&#39;)
          .then(function (response) {
            vm.answer = _.capitalize(response.data.answer)
          })
          .catch(function (error) {
            vm.answer = &#39;Error! Could not reach the API. &#39; + error
          })
      },
      // 这是我们为判定用户停止输入等待的毫秒数      500
    )
  }
})
</script>
Copy after login

Result:

In this example, using the watch option allows us to perform an asynchronous operation (access an API), limit how often we perform the operation, and when we Set up intermediate states before getting to the final result. These are things that computed properties cannot do.

I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!

Related reading:

vue life cycle, vue instance, template syntax

Front-end WeChat sharing jssdk config:invalid signature Wrong signature Solution

#A front-end interview experience

The above is the detailed content of Computed properties and listener use cases for VUE. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

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

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use magnet links How to use magnet links Feb 18, 2024 am 10:02 AM

Magnet link is a link method for downloading resources, which is more convenient and efficient than traditional download methods. Magnet links allow you to download resources in a peer-to-peer manner without relying on an intermediary server. This article will introduce how to use magnet links and what to pay attention to. 1. What is a magnet link? A magnet link is a download method based on the P2P (Peer-to-Peer) protocol. Through magnet links, users can directly connect to the publisher of the resource to complete resource sharing and downloading. Compared with traditional downloading methods, magnetic

How to use mdf and mds files How to use mdf and mds files Feb 19, 2024 pm 05:36 PM

How to use mdf files and mds files With the continuous advancement of computer technology, we can store and share data in a variety of ways. In the field of digital media, we often encounter some special file formats. In this article, we will discuss a common file format - mdf and mds files, and introduce how to use them. First, we need to understand the meaning of mdf files and mds files. mdf is the extension of the CD/DVD image file, and the mds file is the metadata file of the mdf file.

What software is crystaldiskmark? -How to use crystaldiskmark? What software is crystaldiskmark? -How to use crystaldiskmark? Mar 18, 2024 pm 02:58 PM

CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

How to download foobar2000? -How to use foobar2000 How to download foobar2000? -How to use foobar2000 Mar 18, 2024 am 10:58 AM

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

How to use NetEase Mailbox Master How to use NetEase Mailbox Master Mar 27, 2024 pm 05:32 PM

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

How to use Baidu Netdisk app How to use Baidu Netdisk app Mar 27, 2024 pm 06:46 PM

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? Apr 26, 2024 am 09:40 AM

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

Simple guide to pip mirror source: easily master how to use it Simple guide to pip mirror source: easily master how to use it Jan 16, 2024 am 10:18 AM

Get started easily: How to use pip mirror source With the popularity of Python around the world, pip has become a standard tool for Python package management. However, a common problem that many developers face when using pip to install packages is slowness. This is because by default, pip downloads packages from Python official sources or other external sources, and these sources may be located on overseas servers, resulting in slow download speeds. In order to improve download speed, we can use pip mirror source. What is a pip mirror source? To put it simply, just

See all articles