📅  最后修改于: 2023-12-03 15:21:04.525000             🧑  作者: Mango
When working with components in Vue, it's common to pass props down to child components. However, what if you need to watch for changes in these props? That's where Vue's watch
functionality comes in.
To watch for changes in a prop, you can use the watch
property in a component's options. Here's an example:
Vue.component('child-component', {
props: ['message'],
watch: {
message(newValue, oldValue) {
console.log(`Prop 'message' changed from ${oldValue} to ${newValue}`);
},
},
});
In this example, we're watching the message
prop and logging any changes to the console.
Another way to watch for changes in props is to use computed properties. Computed properties can be dependent on props and will update whenever the prop changes. Here's an example:
Vue.component('child-component', {
props: ['message'],
computed: {
messageLength() {
return this.message.length;
},
},
});
In this example, we're using a computed property to watch for changes in the message
prop. Whenever the message
prop changes, the messageLength
computed property will update as well.
You can also combine watchers and computed properties to create more complex functionality. Here's an example:
Vue.component('child-component', {
props: ['message'],
data() {
return {
reversedMessage: '',
};
},
watch: {
message(newValue) {
this.reversedMessage = newValue.split('').reverse().join('');
},
},
computed: {
messageLength() {
return this.message.length;
},
},
});
In this example, we're using a watcher to update a reversedMessage
data property whenever the message
prop changes. We're also using a computed property to watch for changes in the message
prop and update the messageLength
computed property.
By using Vue's watch
functionality, you can easily watch for changes in props passed down to child components. And by combining watchers and computed properties, you can create even more complex functionality.