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: '#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).
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: '',
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: '',
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!
Netflix's Frontend: Examples and Applications of React (or Vue)Apr 16, 2025 am 12:08 AMNetflix uses React as its front-end framework. 1) React's componentized development model and strong ecosystem are the main reasons why Netflix chose it. 2) Through componentization, Netflix splits complex interfaces into manageable chunks such as video players, recommendation lists and user comments. 3) React's virtual DOM and component life cycle optimizes rendering efficiency and user interaction management.
The Frontend Landscape: How Netflix Approached its ChoicesApr 15, 2025 am 12:13 AMNetflix's choice in front-end technology mainly focuses on three aspects: performance optimization, scalability and user experience. 1. Performance optimization: Netflix chose React as the main framework and developed tools such as SpeedCurve and Boomerang to monitor and optimize the user experience. 2. Scalability: They adopt a micro front-end architecture, splitting applications into independent modules, improving development efficiency and system scalability. 3. User experience: Netflix uses the Material-UI component library to continuously optimize the interface through A/B testing and user feedback to ensure consistency and aesthetics.
React vs. Vue: Which Framework Does Netflix Use?Apr 14, 2025 am 12:19 AMNetflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema
The Choice of Frameworks: What Drives Netflix's Decisions?Apr 13, 2025 am 12:05 AMNetflix mainly considers performance, scalability, development efficiency, ecosystem, technical debt and maintenance costs in framework selection. 1. Performance and scalability: Java and SpringBoot are selected to efficiently process massive data and high concurrent requests. 2. Development efficiency and ecosystem: Use React to improve front-end development efficiency and utilize its rich ecosystem. 3. Technical debt and maintenance costs: Choose Node.js to build microservices to reduce maintenance costs and technical debt.
React, Vue, and the Future of Netflix's FrontendApr 12, 2025 am 12:12 AMNetflix mainly uses React as the front-end framework, supplemented by Vue for specific functions. 1) React's componentization and virtual DOM improve the performance and development efficiency of Netflix applications. 2) Vue is used in Netflix's internal tools and small projects, and its flexibility and ease of use are key.
Vue.js in the Frontend: Real-World Applications and ExamplesApr 11, 2025 am 12:12 AMVue.js is a progressive JavaScript framework suitable for building complex user interfaces. 1) Its core concepts include responsive data, componentization and virtual DOM. 2) In practical applications, it can be demonstrated by building Todo applications and integrating VueRouter. 3) When debugging, it is recommended to use VueDevtools and console.log. 4) Performance optimization can be achieved through v-if/v-show, list rendering optimization, asynchronous loading of components, etc.
Vue.js and React: Understanding the Key DifferencesApr 10, 2025 am 09:26 AMVue.js is suitable for small to medium-sized projects, while React is more suitable for large and complex applications. 1. Vue.js' responsive system automatically updates the DOM through dependency tracking, making it easy to manage data changes. 2.React adopts a one-way data flow, and data flows from the parent component to the child component, providing a clear data flow and an easy-to-debug structure.
Vue.js vs. React: Project-Specific ConsiderationsApr 09, 2025 am 12:01 AMVue.js is suitable for small and medium-sized projects and fast iterations, while React is suitable for large and complex applications. 1) Vue.js is easy to use and is suitable for situations where the team is insufficient or the project scale is small. 2) React has a richer ecosystem and is suitable for projects with high performance and complex functional needs.


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

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.







