学习日记--关于vue.js 非父子元素传值的测试

前言,非父子模块传值能否实时获取呢?

测试一:
父到子
结果:,顺利接受到123。
代码:

// 媒介js文件   bus.js
import Vue from 'vue'
export default new Vue()

// 父组件
<template>
  <demo-val></demo-val>
</template>
<script>
  import demoVal from './demo2.vue'
  import bus from './bus.js'
  export default {
    name: '',
    components: {
      demoVal
    },
    mounted(){
      bus.$emit('val',123)
    }
  }
</script>

// 子组件
<template>
    <div>demo2</div>
</template>
<script>
  import bus from './bus.js'
  export default {
    name: "Demo2",
    mounted() {
      bus.$on('val', (data) => {
        console.log(data)
      })
    }
  }
</script>

测试二:
子到父
结果:不能,但是在加载子组件之后,再修改父组件时就能得到123。说明可以传值,但是必须要先让传值放=方生成才行。

// bus.js
import Vue from 'vue'
export default new Vue()

// 父组件
<template>
  <demo-val></demo-val>
</template>
<script>
  import demoVal from './demo2.vue'
  import bus from './bus.js'
  export default {
    name: '',
    components: {
      demoVal
    },
    mounted(){
      bus.$on('val', (data) => {
        console.log(data)
      })
    }
  }
</script>

// 子组件
<template>
    <div>demo2</div>
</template>
<script>
  import bus from './bus.js'
  export default {
    name: "Demo2",
    mounted() {
      bus.$emit('val',123)
    }
  }
</script>

测试三:
兄弟组件中
2兄弟组件中emil值,不能被3组件接受,但是把3组件提到2位置就可以。……我也不知道是为什么…………。

// 父组件
<template>
  <div>
    <demo-val2></demo-val2>
    <demo-val3></demo-val3>
  </div>
</template>
<script>
  import demoVal2 from './demo2.vue'
  import demoVal3 from './demo3.vue'
  export default {
    name: '',
    components: {
      demoVal2,
      demoVal3
    }
  }
</script>

// 兄弟组件1
<template>
  <div>demo2</div>
</template>
<script>
  import bus from './bus.js'
  export default {
    name: "demo2",
    mounted() {
      console.log(2222)
      bus.$emit('val', 'toval')
    }
  }
</script>

// 兄弟组件2
<template>
  <div>demo3</div>
</template>
<script>
  import bus from './bus.js'
  export default {
    name: "demo3",
    mounted() {
      console.log(3333)
      bus.$on('val', (data) => {
        console.log(data)
      })
    }
  }
</script>

疑惑解答:
在这里插入图片描述

posted @ 2022-12-06 22:21  轻风细雨_林木木  阅读(11)  评论(0编辑  收藏  举报