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 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>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: '#app', data() { return { input: '', languages: [] } }, methods: { handleSearch() { this.languages = [ 'JavaScript', 'Ruby', 'Scala', 'Python', 'Java', 'Kotlin', 'Elixir' ].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).
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>
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: '', 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>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: '', languages: [] } }, watch: { input: { handler() { this.languages = [ 'JavaScript', 'Ruby', 'Scala', 'Python', 'Java', 'Kotlin', 'Elixir' ].filter(item => item.toLowerCase().includes(this.input.toLowerCase())) }, immediate: true } }})
在这里,我已经将观察者作为对象(而不是函数)。这样,我可以指定一个immediate
属性,该属性将导致观察者在安装组件后立即触发。这具有填充列表的效果。然后,运行的函数在该handler
属性中。
正如他们所说,强大的力量伴随着巨大的责任。Vue为您提供了构建出色应用程序所需的超能力。知道何时使用它们是建立用户喜爱的关键。方法、计算属性和观察者是您可以使用的超能力的一部分。展望未来,一定要好好利用它们!
相关推荐:
更多编程相关知识,请访问:编程入门!!
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!