父组件包含一个按钮和一个颜色选择器。子组件有一个绑定的背景颜色,默认情况下是灰色。父组件通过$refs访问子组件并改变子组件的背景颜色,效果会即时反映在子组件中。
时间: 2024-11-21 20:08:40 浏览: 22
这是一个常见的Vue.js父子组件通信示例。在这个场景中,父组件作为一个容器,包含了交互元素如按钮和颜色选择器,而子组件负责渲染背景颜色并提供接口来接收和处理变化。
1. 父组件(通常是一个`<template>`标签)里,有个按钮触发事件,比如`@click="changeColor"`,当用户点击这个按钮时,会调用`methods`里的`changeColor`方法。
```html
<template>
<div>
<color-picker ref="colorPicker" :bg-color="backgroundColor"></color-picker>
<button @click="changeColor">更改颜色</button>
</div>
</template>
```
2. `changeColor`方法会通过`this.$refs.colorPicker`获取到子组件的引用,并设置其`bg-color`属性,即子组件的颜色值:
```javascript
<script>
export default {
methods: {
changeColor() {
this.$refs.colorPicker.bgColor = 'newColor'; // 新的颜色值
}
},
data() {
return {
backgroundColor: 'gray', // 默认背景颜色
};
},
};
</script>
```
3. 子组件(假设名为`ColorPicker.vue`)通常接收`bg-color`作为props,并将其应用到组件的样式上。如果需要实时更新,可能还会监听props的变化并相应地更新DOM。
```vue
<template>
<div style="background-color: {{ bgColor }}">
<!-- 子组件内容 -->
</div>
</template>
<script>
export default {
props: ['bgColor'],
watch: {
bgColor(newColor) {
this.$el.style.backgroundColor = newColor;
}
}
};
</script>
```
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)