vue快速入门(四十)非父子组件通信

注释很详细,直接上代码

上一篇

新增内容

  1. 媒介js的创建
  2. 发送组件发送事件示例
  3. 接收组件接收事件示例

源码

App.vue

<template>
  <div id="app">
    <TessFirst></TessFirst>
    <TestSecond></TestSecond>
  </div>
</template>
<script>
import TessFirst from "./components/TestFirst.vue";
import TestSecond from "./components/TestSecond.vue";
export default {
  name: "App",
  components: {
    TessFirst,
    TestSecond
  },
  data() {
    return {
    };
  },
  methods: {
  },
};
</script>
<style>
</style>

bus.js

import Vue from 'vue'
// 创建一个空的vue实例
export default new Vue()

TestFirst.vue

<template>
  <div>
    发送组件:
    <input type="text" v-model="sendMessage" @input="handleChange" />
  </div>
</template>
<script>
//以bus为桥梁
import bus from "../bus.js";
export default {
  data() {
    return {
      sendMessage: "",
    };
  },
  methods: {
    //发送消息
    handleChange(e) {
      //向bus发送方法与数据
      bus.$emit("getMessage", e.target.value);
    },
  }
};
</script>

<style lang="less" scoped></style>

TestSecond.vue

<template>
  <div>接收组件的值:{{ getMessage }}</div>
</template>

<script>
//以bus为媒介接收订阅事件
import bus from "../bus.js";
export default {
  data() {
    return {
      getMessage: "",
    };
   
  },
  created() {
      //监听事件,接收订阅事件并渲染
      bus.$on("getMessage", (val) => {
        this.getMessage = val;
      });
    }
};
</script>

<style lang="scss" scoped></style>

效果演示

在这里插入图片描述

相关推荐

  1. Vue3父子组件通信

    2024-04-24 18:14:02       62 阅读
  2. Vue父子组件通信代码示例

    2024-04-24 18:14:02       40 阅读
  3. Vue组件通信讲解[父子组件通信]

    2024-04-24 18:14:02       41 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-24 18:14:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-24 18:14:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-04-24 18:14:02       82 阅读
  4. Python语言-面向对象

    2024-04-24 18:14:02       91 阅读

热门阅读

  1. 【nginx安装内置的http_image_filter_module】

    2024-04-24 18:14:02       34 阅读
  2. 卡口车辆智能检索系统

    2024-04-24 18:14:02       31 阅读
  3. SQL仓库

    2024-04-24 18:14:02       30 阅读
  4. 嵌入式Linux—Framebuffer应用编程

    2024-04-24 18:14:02       38 阅读
  5. 研发管理规范

    2024-04-24 18:14:02       29 阅读
  6. 红帽系统Redhat忘记密码,重置root密码

    2024-04-24 18:14:02       31 阅读
  7. 神经网络与深度学习(四)

    2024-04-24 18:14:02       25 阅读
  8. ORA-25153:临时表空间为空

    2024-04-24 18:14:02       30 阅读
  9. 程序员的压力缓解之道:寻找工作与生活的平衡

    2024-04-24 18:14:02       32 阅读
  10. 孩子如何才能学好Scratch

    2024-04-24 18:14:02       26 阅读