search
HomeWeb Front-endVue.jsThe difference between Computed properties, Methods and Watch in Vue

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() {}
  }
})

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

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

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>

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 id="Language-nbsp-Search">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>

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() }
})

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 id="Language-nbsp-Search">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>

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())
      })
    }
  }
})

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}`
  }
}

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

观察者

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

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

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

<div id="app">
  <h2 id="Language-nbsp-Search">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>

然后我们的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
    }
  }})

在这里,我已经将观察者作为对象(而不是函数)。这样,我可以指定一个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
This article is reproduced at:sitepoint. If there is any infringement, please contact admin@php.cn delete
Vue常见面试题汇总(附答案解析)Vue常见面试题汇总(附答案解析)Apr 08, 2021 pm 07:54 PM

本篇文章给大家分享一些Vue面试题(附答案解析)。有一定的参考价值,有需要的朋友可以参考一下,希望对大家有所帮助。

5 款适合国内使用的 Vue 移动端 UI 组件库5 款适合国内使用的 Vue 移动端 UI 组件库May 05, 2022 pm 09:11 PM

本篇文章给大家分享5 款适合国内使用的 Vue 移动端 UI 组件库,希望对大家有所帮助!

vue中props可以传递函数吗vue中props可以传递函数吗Jun 16, 2022 am 10:39 AM

vue中props可以传递函数;vue中可以将字符串、数组、数字和对象作为props传递,props主要用于组件的传值,目的为了接收外面传过来的数据,语法为“export default {methods: {myFunction() {// ...}}};”。

手把手带你利用vue3.x绘制流程图手把手带你利用vue3.x绘制流程图Jun 08, 2022 am 11:57 AM

利用vue3.x怎么绘制流程图?下面本篇文章给大家分享基于 vue3.x 的流程图绘制方法,希望对大家有所帮助!

聊聊vue指令中的修饰符,常用事件修饰符总结聊聊vue指令中的修饰符,常用事件修饰符总结May 09, 2022 am 11:07 AM

本篇文章带大家聊聊vue指令中的修饰符,对比一下vue中的指令修饰符和dom事件中的event对象,介绍一下常用的事件修饰符,希望对大家有所帮助!

如何覆盖组件库样式?React和Vue项目的解决方法浅析如何覆盖组件库样式?React和Vue项目的解决方法浅析May 16, 2022 am 11:15 AM

如何覆盖组件库样式?下面本篇文章给大家介绍一下React和Vue项目中优雅地覆盖组件库样式的方法,希望对大家有所帮助!

通过9个Vue3 组件库,看看聊前端的流行趋势!通过9个Vue3 组件库,看看聊前端的流行趋势!May 07, 2022 am 11:31 AM

本篇文章给大家分享9个开源的 Vue3 组件库,通过它们聊聊发现的前端的流行趋势,希望对大家有所帮助!

react与vue的虚拟dom有什么区别react与vue的虚拟dom有什么区别Apr 22, 2022 am 11:11 AM

react与vue的虚拟dom没有区别;react和vue的虚拟dom都是用js对象来模拟真实DOM,用虚拟DOM的diff来最小化更新真实DOM,可以减小不必要的性能损耗,按颗粒度分为不同的类型比较同层级dom节点,进行增、删、移的操作。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft