vue 子组件如何监听父组件传入来的值并第一时间打印出来,可以举出2个例子吗
时间: 2023-12-29 19:03:40 浏览: 31
可以使用Vue的props属性来实现子组件监听父组件传入的值。具体实现方法如下:
1. 通过v-bind绑定父组件传入的值到子组件的props属性中:
```html
<!-- 父组件 -->
<template>
<div>
<child-component :message="message"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue'
export default {
components: {
ChildComponent
},
data() {
return {
message: 'Hello World!'
}
}
}
</script>
<!-- 子组件 -->
<template>
<div>
<p>{{ message }}</p>
</div>
</template>
<script>
export default {
props: {
message: String
},
mounted() {
console.log(this.message)
}
}
</script>
```
2. 直接在子组件的模板中使用父组件传入的值,并在子组件的mounted钩子函数中打印出来:
```html
<!-- 父组件 -->
<template>
<div>
<child-component></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue'
export default {
components: {
ChildComponent
},
data() {
return {
message: 'Hello World!'
}
}
}
</script>
<!-- 子组件 -->
<template>
<div>
<p>{{ $parent.message }}</p>
</div>
</template>
<script>
export default {
mounted() {
console.log(this.$parent.message)
}
}
</script>
```
以上两种方法都可以实现子组件监听父组件传入的值并打印出来。第一个方法是通过props属性来实现的,第二个方法是通过$parent属性来实现的。需要注意的是,第二种方法中$parent属性只有在子组件没有被包裹在其它组件中时才能使用。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)