vue父子组件传递数据-兄弟组件传递数据

1.父向子传递数据

父组件中传递数据 ↓ ↓ ↓ ↓ ↓ ↓

<template>
  <div>
    <child :message="parentMessage"></child>
  </div>
</template>

<script>
import Child from './Child.vue'

export default {
  components: {
    Child
  },
  data() {
    return {
      parentMessage: 'Hello from parent'
    }
  }
}
</script>

子组件中接收数据 ↓ ↓ ↓ ↓ ↓ ↓

<template>
  <div>{{ message }}</div>
</template>

<script>
export default {
  props: {
    message: {
      type: String,
      default: ''
    }
  }
}
</script>

2.子组件向父组件传递数据

子组件中派发事件 ↓ ↓ ↓ ↓ ↓ ↓

<template>
  <div>
    <button @click="sendMessage">Send message to parent</button>
  </div>
</template>
<script>
export default {
  methods: {
    sendMessage() {
      this.$emit('message', 'Hello from child')
    }
  }
}
</script>

父组件中监听事件并接收数据 ↓ ↓ ↓ ↓ ↓ ↓

<template>
  <div>
    <child @message="receiveMessage"></child>
    <div>{{ parentMessage }}</div>
  </div>
</template>
<script>
import Child from './Child.vue'
export default {
  components: {
    Child
  },
  data() {
    return {
      parentMessage: ''
    }
  },
  methods: {
    receiveMessage(message) {
      this.parentMessage = message
    }
  }
}
</script>

3.子组件通过$emit方法调用父组件的函数

父组件中定义函数↓ ↓ ↓ ↓ ↓ ↓

<template>
  <div>
    <child @childClick="handleClick"></child>
  </div>
</template>
<script>
import Child from './Child.vue'
export default {
  components: {
    Child
  },
  methods: {
    handleClick(event) {
      console.log('Received: ' + event)
    }
  }
}
</script>

子组件中调用父组件的函数↓ ↓ ↓ ↓ ↓ ↓

<template>
  <div>
    <button @click="emitClick">Send message to parent</button>
  </div>
</template>
<script>
export default {
  methods: {
    emitClick() {
      this.$emit('childClick', 'Hello from child')
    }
  }
}
</script>

4.父组件调用子组件的函数(ref,$resf)

子组件↓ ↓ ↓ ↓ ↓ ↓

<template>
  <div>
    <p>{{ message }}</p>
  </div>
</template>
<script>
export default {
  data() {
    return {
      message: 'Hello from child component!'
    }
  },
  methods: {
    childFunc(param1, param2) {
      console.log(`Child function called with parameters: ${param1}, ${param2}`);
      this.message = 'Child function was called';
    }
  }
}
</script>

父组件↓ ↓ ↓ ↓ ↓ ↓

通过this.$refs.childRef获取子组件的引用,并调用其中的childFunc()函数。在这里,我们传入了两个参数:'Hello'和'World'。

<template>
  <div>
    <button @click="callChildFunc">Call child component function</button>
    <Child ref="childRef"></Child>
  </div>
</template>
<script>
import Child from './Child.vue';

export default {
  components: {
    Child
  },
  methods: {
    callChildFunc() {
      this.$refs.childRef.childFunc('Hello', 'World');
    }
  }
}
</script>

5.兄弟组件传递数据(vue3)

兄弟A↓ ↓ ↓ ↓ ↓ ↓

<template>
  <div>
    <p>{{ dataFromA }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      dataFromA: 'Data from Component A'
    }
  },
  provide: {
    sharedData: this.dataFromA
  }
}
</script>

兄弟B↓ ↓ ↓ ↓ ↓ ↓

<template>
  <div>
    <p>{{ sharedData }}</p>
  </div>
</template>

<script>
export default {
  inject: ['sharedData']
}
</script>

兄弟组件传递数据(vue2)

兄弟A↓ ↓ ↓ ↓ ↓ ↓

<template>
  <div>
    <p>{{ dataFromA }}</p>
    <button @click="emitData">Send Data to Component B</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      dataFromA: 'Data from Component A'
    }
  },
  methods: {
    emitData() {
      this.$emit('my-event', this.dataFromA);
    }
  }
}
</script>

兄弟B↓ ↓ ↓ ↓ ↓ ↓

<template>
  <div>
    <p>{{ dataFromA }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      dataFromA: null
    }
  },
  mounted() {
    this.$root.$on('my-event', (data) => {
      this.dataFromA = data;
    });
  },
  destroyed() {
    this.$root.$off('my-event');
  }
}
</script>

这就是一个 Vue 2 的兄弟组件传递数据的例子。需要注意的是,在 Vue 2 中使用 $root 不太推荐,因为它会使代码变得难以维护。你可以使用 Vuex 或 Bus 来实现更好的数据共享和管理。

### 实现Vue2兄弟组件间的数据传递Vue2项目中,有多种方法可以实现在兄弟组件之间传递数据。以下是几种常见的解决方案: #### 方法一:通过共同的父级组件通信 这是最推荐的方式之一,在这种情况下,两个子组件共享同一个父组件的状态。 ```html <!-- ParentComponent.vue --> <template> <div class="parent"> <ChildA :messageFromParent="sharedMessage" @updateSharedMessage="handleUpdate"></ChildA> <ChildB :messageFromParent="sharedMessage"></ChildB> </div> </template> <script> export default { name: 'ParentComponent', data() { return { sharedMessage: '' } }, methods: { handleUpdate(newMsg) { this.sharedMessage = newMsg; } } } </script> ``` 对于`ChildA`和`ChildB`这两个兄弟组件来说,则分别定义接收属性以及发送更新消息的方法: ```javascript // ChildA.vue 和 ChildB.vue 中的部分代码片段 props: ['messageFromParent'], methods: { sendMessageToSibling(msg){ this.$emit('updateSharedMessage', msg); } } ``` 这种方法利用了父子间的prop下传与event上抛机制来间接完成兄弟间的通讯[^1]。 #### 方法二:使用Event Bus (全局事件总线) 创建一个新的Vue实例作为中央事件中心(event bus),用于不同组件之间的解耦合通信。 ```javascript // eventBus.js 文件内 import Vue from 'vue'; const EventBus = new Vue(); export default EventBus; ``` 然后可以在任何地方导入并使用这个bus对象来进行监听或分发自定义事件: ```javascript // ComponentOne.vue 发送者 import EventBus from './path/to/eventBus'; ... this.$nextTick(() => { EventBus.$emit('some-event-name', payload); }); ... // AnotherComponent.vue 接收方 import EventBus from './path/to/eventBus'; created(){ EventBus.$on('some-event-name',(data)=>{ console.log(data); }); }, beforeDestroy () { // 清除事件监听器很重要 EventBus.$off('some-event-name'); } ``` 这种方式适合于简单的应用结构,但对于大型应用程序可能会变得难以维护。 #### 方法三:Vuex状态管理模式 当涉及到多个层次嵌套或者跨模块的数据交互时,采用集中式的存储管理工具如Vuex会更加合适。它允许我们在store中保存公共变量,并让各个组件订阅这些变化。 ```javascript // store/index.js 配置文件的一部分 state:{ count:0, }, mutations:{ increment(state,payload){ state.count +=payload; } } // AnyComponent.vue 使用方式如下所示 computed:mapState(['count']), methods: mapMutations(['increment']) <button v-on:click="increment(1)">Increment Counter</button> <p>Current Count is {{ count }}</p> ``` 以上三种方案都可以有效地解决Vue2中的兄弟组件沟通问题,具体选择取决于项目的规模和个人偏好。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Mars空港

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值