- 步骤:
- 在传送的组件中,通过
$emit
触发一个自定义事件,并将需要的数据传递出去。
- 在接收传送内容的组件中,使用
v - on
或 @
语法监听这个自定义事件,并定义对应的处理函数。
- 代码示例:
<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>