vue2 组件共享数据17 父子组件 子向父组件 兄弟组件

父子组件:

  父只管定义数据和传数据

  子只管接收数据和声明数据

父:
<hello :msg="message" :user="username"></hello> import hello from '@/components/HelloWorld.vue' data() { return { username: 'admin', message:'传值测试', } }, components:{ hello },

  

子:
{{msg}}={{user}}
props:['msg','user'],

  

子组件的值不建议修改,保持只读就好

 

 

子传父:

父组件:
<hello @fromCount="getCount"></hello>
data() {
    return {
      countSon:0,
    }
  },
  components:{
    hello
  },
methods: {
    getCount(Val){
      this.countSon = Val
    }
  },
子组件:
<p>组件{{count}}</p> <button @click="add">+1</button>
data() {
    return {
      count:0,
    }
  },
methods: {
    add(){
      this.count += 1
      this.$emit('fromCount',this.count)
    }
  },
 
 
 
兄弟组件:
 需要在兄弟组件之间创建一个eventBus的模块
 在发送方调用bus.$emit('事件名称',发送的数据)的触发自定义事件
 在接受数据方bus.$on('事件名称',事件处理函数)的方法注册一个自定义事件

 

 

 

 发送方:

<template>
  <div class="hello">
    接收方
    <button @click="send">发送</button>
  </div>
</template>

<script>
import bus from './eventBus.js'
export default {
  data() {
    return {
      str:'C罗yyds'
    }
  },
 
  methods: {
    send(){
      bus.$emit('share',this.str)
    }
  },
}
</script>
 
 
中间件:
import Vue from 'vue'

export default new Vue()

 

接收方:

mystr:{{mystr}}
 
 data() {
    return {
      mystr:'',
    }
  },
  created() {
    bus.$on('share',(Val)=>{
      console.log('ke事件触发',Val);
      this.mystr = Val
    })
  },
posted @ 2022-11-28 16:30  文采呱呱  阅读(27)  评论(0编辑  收藏  举报