文章目录
1、mounted 和 beforeDestroy
1.1、mounted
mounted() 钩子函数在组件被挂载到 DOM 后调用。代码 document.addEventListener(“click”, this.closeMenu) 在组件挂载后,为整个文档添加了一个点击事件监听器,当用户在文档任何地方点击时,都会触发 this.closeMenu 方法。
<script>
export default {
mounted() {
//动作
},
1.2、beforeDestroy
beforeDestroy() 钩子函数在组件被销毁之前调用。代码 document.removeEventListener(“click”, this.closeMenu) 在组件销毁之前,移除之前添加的点击事件监听器,避免组件销毁后仍然存在监听器,导致潜在的错误或内存泄漏。
<script>
export default {
beforeDestroy() {
//动作
},
2、父组件向子组件传递参数 props
2.1、子组件定义
<script>
export default {
props: ["clientX", "clientY", "clickIndex","tagsLength"],
//其余内容略
}
2.2、父组件调用子组件并传参
<template>
//其余略
<TagsMenu v-show="isShowTagsMenu" :clientX="clientX" :clientY="clientY" :clickIndex="clickIndex"
:tagsLength="tags.length" />
//其余略
</template>
<script>
import TagsMenu from './TagsMenu.vue';
//其余略
3、完整例子
3.1、父组件 Tags.vue
<template>
<div class="tags">
<!-- .native 用法:在 Vue.js 中,.native 修饰符用于监听原生 DOM 事件,而不是 Vue 组件的自定义事件。
例如,@contextmenu.native="rightClick($event)"
.prevent 阻止浏览器默认行为
表示你希望监听原生的 contextmenu 事件(通常是右键点击),