MST

星途 面试题库

面试题:Vue Teleport 中如何处理跨组件传递事件?

在使用 Vue Teleport 将一个组件的内容传送到另一个组件的指定位置后,假设传送的组件中有一个按钮点击事件,要在接收传送内容的组件中处理该点击事件,应该如何实现?请描述具体步骤及相关代码示例。
20.5万 热度难度
前端开发Vue

知识考点

AI 面试

面试题答案

一键面试
  1. 步骤
    • 在传送的组件中,通过 $emit 触发一个自定义事件,并将需要的数据传递出去。
    • 在接收传送内容的组件中,使用 v - on@ 语法监听这个自定义事件,并定义对应的处理函数。
  2. 代码示例
    • 传送的组件(例如 Sender.vue
<template>
  <button @click="handleClick">点击我</button>
</template>

<script>
export default {
  methods: {
    handleClick() {
      this.$emit('custom - click', '这是传递的数据');
    }
  }
};
</script>
  • 接收传送内容的组件(例如 Receiver.vue
<template>
  <div>
    <teleport to="#target - container">
      <Sender @custom - click="handleCustomClick"/>
    </teleport>
  </div>
</template>

<script>
import Sender from './Sender.vue';

export default {
  components: {
    Sender
  },
  methods: {
    handleCustomClick(data) {
      console.log('接收到点击事件,数据为:', data);
    }
  }
};
</script>
  • index.html 或相关入口文件中添加 #target - container
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF - 8">
  <meta name="viewport" content="width=device - width, initial - scale = 1.0">
  <title>Document</title>
</head>

<body>
  <div id="app"></div>
  <div id="target - container"></div>
  <script src="your - vue - script.js"></script>
</body>

</html>