vue如何监听 孙组件的 参数变化
时间: 2023-12-29 21:02:36 浏览: 36
要监听孙组件的参数变化,可以使用 Vue.js 中的 `$watch` 方法。具体步骤如下:
1. 在父组件中引入孙组件,并在模板中使用该组件。
2. 在父组件中使用 `$refs` 获取孙组件的实例。
3. 在父组件的 `mounted` 生命周期钩子函数中,使用 `$watch` 方法监听孙组件的参数变化。
例如,假设父组件为 `ParentComponent`,孙组件为 `GrandchildComponent`,要监听孙组件的 `prop1` 参数变化,代码如下:
```html
<template>
<div>
<grandchild-component ref="grandchild"></grandchild-component>
</div>
</template>
<script>
import GrandchildComponent from './GrandchildComponent.vue';
export default {
components: {
GrandchildComponent
},
mounted() {
this.$watch(() => {
return this.$refs.grandchild.prop1;
}, (newVal, oldVal) => {
console.log(`prop1 changed from ${oldVal} to ${newVal}`);
});
}
}
</script>
```
在上面的代码中,我们使用了 `$refs` 来获取孙组件实例,并在 `mounted` 钩子函数中使用 `$watch` 方法监听 `prop1` 的变化。当 `prop1` 发生变化时,控制台将打印出变化前后的值。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)