Table of Contents
Method" >Method
Computed Properties" >Computed Properties
观察者" >观察者
结论" >结论
Home Web Front-end Vue.js The difference between Computed properties, Methods and Watch in Vue

The difference between Computed properties, Methods and Watch in Vue

Sep 27, 2020 pm 06:09 PM
computed methods vue watch

The difference between Computed properties, Methods and Watch in Vue

For those who are just starting to learn Vue, the differences between methods, computed properties, and observers can be a little confusing. Although you can often use each of them to accomplish more or less the same thing, it's important to know in what ways they are better than the others.

In this quick tip, we will look at these three important aspects of Vue applications and their use cases. We'll build the same search component using each of these three methods.

Method

Method is more or less what you would expect -- a function that is a property of an object. You can use methods to react to events that occur in the DOM, or you can call them from elsewhere in the component (for example, in a computed property or observer). Methods are used to group commonly used functionality -- for example, for handling form submissions or building reusable functionality, such as making Ajax requests.

You can create a method in a Vue instance inside the methods object:

new Vue({
  el: "#app",
  methods: {
    handleSubmit() {}
  }
})
Copy after login

When you want to use it in a template, you can do the following:

<div id="app">
  <button @click="handleSubmit">
    Submit
  </button>
</div>
Copy after login

We use the v-on directive to attach the event handler to our DOM element, which can also be abbreviated with the @ notation.

The handleSubmit method will be called every time the button is clicked. For example, when you want to pass the parameters required in the method body, you can do the following:

<div id="app">
  <button @click="handleSubmit(event)">
    Submit
  </button>
</div>
Copy after login

Here, we pass an Event object, which prevents us from Prevents the browser's default action when submitting a form.

However, since we are attaching events using directives, we can achieve the same thing more elegantly using modifiers: @click.stop="handleSubmit".

Now, let’s look at an example of using a method to filter a list of data in an array.

In the demo, we want to render the data list and search box. Whenever the user enters a value in the search box, the rendered data changes. The template will look like this:

<div id="app">
  <h2>Language Search</h2>

  <div class="form-group">
    <input
      type="text"
      v-model="input"
      @keyup="handleSearch"
      placeholder="Enter language"
      class="form-control"
    />
  </div>

  <ul v-for="(item, index) in languages" class="list-group">
    <li class="list-group-item" :key="item">{{ item }}</li>
  </ul>
</div>
Copy after login

As you can see, we are referencing a handleSearch method that will be called every time the user types in the search field. We need to create methods and data:

new Vue({
  el: &#39;#app&#39;,
  data() {
    return {
      input: &#39;&#39;,
      languages: []
    }
  },
  methods: {
    handleSearch() {
      this.languages = [
        &#39;JavaScript&#39;,
        &#39;Ruby&#39;,
        &#39;Scala&#39;,
        &#39;Python&#39;,
        &#39;Java&#39;,
        &#39;Kotlin&#39;,
        &#39;Elixir&#39;
      ].filter(item => item.toLowerCase().includes(this.input.toLowerCase()))
    }
  },
  created() { this.handleSearch() }
})
Copy after login

handleSearch method updates the listed items with the value of the input field. One thing to note is that in the methods object you don't need to reference the method using this.handleSearch (you have to do this in react).

Computed Properties

Although the search in the above example works as expected, a more elegant solution is to use Computed properties. Computed properties are very convenient for combining new data from existing resources, and one of their big advantages over methods is that their output can be cached. This means that if something on the page that is not related to the computed property changes and the UI re-renders, the cached results will be returned and the computed property will not be recalculated, saving us a potentially expensive operation.

Computed properties allow us to perform calculations on the fly using available data. In this case, we have a series of items that need to be sorted. We want to sort when the user enters a value in the input field.

Our template looks almost the same as the previous iteration, except we passed a computed property (filteredList) to the v-for directive:

<div id="app">
  <h2>Language Search</h2>
  <div class="form-group">
    <input
      type="text"
      v-model="input"
      placeholder="Enter language"
      class="form-control"
    />
  </div>
  <ul v-for="(item, index) in filteredList" class="list-group">
    <li class="list-group-item" :key="item">{{ item }}</li>
  </ul>
</div>
Copy after login

The script part is slightly different. We declare the language in the data attribute (previously this was an empty array), instead of moving the method to a method in a computed property:

new Vue({
  el: "#app",
  data() {
    return {
      input: &#39;&#39;,
      languages: [
        "JavaScript",
        "Ruby",
        "Scala",
        "Python",
        "Java",
        "Kotlin",
        "Elixir"
      ]
    }
  },
  computed: {
    filteredList() {
      return this.languages.filter((item) => {
        return item.toLowerCase().includes(this.input.toLowerCase())
      })
    }
  }
})
Copy after login

filteredList computed The property will contain an array of items containing the input field values. On the first render (when the input field is empty), the entire array is rendered. When the user enters a value in the field, filteredList will return an array containing the value entered in the field.

When using calculated properties, the data to be calculated must be available, otherwise an application error will result.

Computed properties create a new filteredList property, that's why we can reference it in the template. Every time a dependency changes, the value of filteredList changes. The easy-to-change dependency here is the value of the input.

最后,请注意,计算属性使我们可以创建一个变量,以在由一个或多个数据属性构建的模板中使用。一个常见的示例是fullName从用户的名字和姓氏创建一个,如下所示:

computed: {
  fullName() {
    return `${this.firstName} ${this.lastName}`
  }
}
Copy after login

在模板中,您可以执行{{fullName}}。每当第一个或最后一个名称的值发生变化时,fullName的值就会发生变化。

观察者

当您希望对发生的更改(例如,对一个道具或数据属性)执行一个操作时,观察者非常有用。正如Vue文档所述,当您希望执行异步或昂贵的操作来响应数据更改时,这是最有用的。

在我们的搜索示例中,我们可以返回到方法示例,并为input data属性设置一个监视程序。然后,我们可以对input值的任何变化做出反应。

首先,让我们还原模板以利用languages data属性:

<div id="app">
  <h2>Language Search</h2>

  <div class="form-group">
    <input
      type="text"
      v-model="input"
      placeholder="Enter language"
      class="form-control"
    />
  </div>

  <ul v-for="(item, index) in languages" class="list-group">
    <li class="list-group-item" :key="item">{{ item }}</li>
  </ul>
</div>
Copy after login

然后我们的Vue实例将如下所示:

new Vue({
  el: "#app",
  data() {
    return {
      input: &#39;&#39;,
      languages: []
    }
  },
  watch: {
    input: {
      handler() {
        this.languages = [
          &#39;JavaScript&#39;,
          &#39;Ruby&#39;,
          &#39;Scala&#39;,
          &#39;Python&#39;,
          &#39;Java&#39;,
          &#39;Kotlin&#39;,
          &#39;Elixir&#39;
        ].filter(item => item.toLowerCase().includes(this.input.toLowerCase()))
      },
      immediate: true
    }
  }})
Copy after login

在这里,我已经将观察者作为对象(而不是函数)。这样,我可以指定一个immediate属性,该属性将导致观察者在安装组件后立即触发。这具有填充列表的效果。然后,运行的函数在该handler属性中。

结论

正如他们所说,强大的力量伴随着巨大的责任。Vue为您提供了构建出色应用程序所需的超能力。知道何时使用它们是建立用户喜爱的关键。方法计算属性观察者是您可以使用的超能力的一部分。展望未来,一定要好好利用它们!

相关推荐:

2020年前端vue面试题大汇总(附答案)

vue教程推荐:2020最新的5个vue.js视频教程精选

更多编程相关知识,请访问:编程入门!!

The above is the detailed content of The difference between Computed properties, Methods and Watch in 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

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 add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

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.

How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

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.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

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.

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

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

What does vue multi-page development mean? What does vue multi-page development mean? Apr 07, 2025 pm 11:57 PM

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

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

How to query the version of vue How to query the version of vue Apr 07, 2025 pm 11:24 PM

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 &lt;script&gt; tag in the HTML file that refers to the Vue file.

How to pass parameters for vue function How to pass parameters for vue function Apr 08, 2025 am 07:36 AM

There are two main ways to pass parameters to Vue.js functions: pass data using slots or bind a function with bind, and provide parameters: pass parameters using slots: pass data in component templates, accessed within components and used as parameters of the function. Pass parameters using bind binding: bind function in Vue.js instance and provide function parameters.

See all articles