首页 > 语言 > JavaScript > 正文

Vue组件间通信方法总结(父子组件、兄弟组件及祖先后代组件间

2024-05-06 15:40:31
字体:
来源:转载
供稿:网友

前言

除了使用 Vuex 方法外,vue 提供了各种各样的组件间通信的方案。文章整理一下父子组件、兄弟组件、祖先后代组件间是如何通信的。 💬

🌊 父子组件通信

props 和 $emit 父子组件通信

子组件有时需要与父组件进行沟通,沟通的方式就是子组件 emit 事件,父组件通过监听这个事件来做进一步动作。而父组件与子组件通信则使用 props

假设这里有一个父组件并引入了一个子组件 my-comp:

<my-comp v-for="msg in msgs" :key="msg.id" :msg="msg"></my-comp>

父组件有一系列 msg 数据需要通过子组件渲染,将 msg 作为 prop 传递给子组件即可:

import MyComp from '@/components/MyComp.vue'export default { name: 'home', components: { MyComp }, data () { return { msgs: [{ id: 1, data: 'hello js' }, { id: 2, data: 'css world' }, { id: 3, data: 'animated style' }] } }}

我们通过点击子组件每一项触发一个事件,父组件监听这个事件去动态改变子组件的 color 样式,这就是父组件监听子组件事件,事件处理函数可以从子组件传递值给父组件:

<my-comp v-for="msg in msgs" :key="msg.id" :msg="msg" :colored="colored" @handle-change-color="handleChangeColor"></my-comp>

首先增加一个事件 handle-change-color 当这个事件被触发时修改名为 color 的 data,然后将 colored 通过 props 传入到子组件:

import MyComp from '@/components/MyComp.vue'export default { name: 'home', components: { // 注册组件 MyComp }, data () { return { colored: false, // 状态 msgs: [{ id: 1, data: 'hello js' }, { id: 2, data: 'css world' }, { id: 3, data: 'animated style' }] } }, methods: { handleChangeColor () { this.colored = !this.colored // 监听事件动态改变 colored } // handleChangeColor (param) { // 子组件触发的事件可能包含参数 }}

然后编辑子组件:

<div> <div @click="handleClick" :style="{color}"> {{msg.id}} - {{msg.data}} ⭕ </div></div>

首先渲染数据,并监听 click 点击事件,当点击触发事件处理函数 handleClick

export default { name: 'MyComp', computed: { color () { // color 为样式 return this.colored ? 'red' : 'black' // 根据父组件传入的 props 动态修改样式 } }, props: ['msg', 'colored'], methods: { handleClick (e) { this.$emit('handle-change-color') // 使用 $emit 方法触发父组件 handle-change-color 事件 // this.$emit('handler', 'param') // 还可以给事件传递参数 } }}

子组件接收 colored 父组件传递来的 prop,返回一个计算后的属性 color,根据 colored 返回不同样式。handleClick 处理当子组件元素被点击时 $emit 派发父组件的 handle-change-color 事件

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选