In Vue.js, mounted
, computed
, and watcher
are all features used to handle data and interactions between the view and the model.
mounted
: This is a lifecycle hook that runs after the Vue instance has been mounted to the DOM. It is used to perform any actions that require access to the mounted DOM elements. For example, you can usemounted
to fetch data from an API and then update the view with the fetched data.
Here's an example of using mounted
:
php<template>
<div>
<p>{{ message }}</p>
</div>
</template>
<script>
export default {
data() {
return {
message: ""
};
},
mounted() {
// Fetch data from an API
fetch("https://api.example.com/data")
.then(response => response.json())
.then(data => {
// Update the message with the fetched data
this.message = data.message;
});
}
};
</script>
In this example, the mounted
hook is used to fetch data from an API and then update the view with the fetched data.
computed
: This is a property that computes a value based on other data properties in the Vue instance. It is used to dynamically compute and cache values based on other data properties, and it can be used in the template to display computed values.
Here's an example of using computed
:
php<template>
<div>
<p>{{ message }}</p>
<p>{{ reversedMessage }}</p>
</div>
</template>
<script>
export default {
data() {
return {
message: "Hello, Vue!"
};
},
computed: {
reversedMessage() {
return this.message.split("").reverse().join("");
}
}
};
</script>
In this example, the computed
property is used to compute a reversed version of the message
data property, and it can be used in the template to display the computed value.
watcher
: This is a feature that watches for changes to a data property and performs an action when the property changes. It is used to perform side effects based on changes to data properties, such as updating other data properties or making API calls.
Here's an example of using watcher
:
php<template>
<div>
<p>{{ message }}</p>
<button @click="incrementCounter">Increment Counter</button>
</div>
</template>
<script>
export default {
data() {
return {
message: "",
counter: 0
};
},
watch: {
counter(newCounterValue) {
// Update the message when the counter changes
this.message = `The counter is now ${newCounterValue}.`;
}
},
methods: {
incrementCounter() {
// Increment the counter when the button is clicked
this.counter++;
}
}
};
</script>
In this example, the watcher
feature is used to watch for changes to the counter
data property and update the message
data property when the counter
changes. The incrementCounter
method is used to increment the counter
when the button is clicked, which triggers the watcher
to update the message
.
No comments:
Post a Comment