• 自定义事件的使用


    绑定自定义事件

    Vue.js中,你可以使用自定义事件来实现组件之间的通信。自定义事件允许你在一个组件中触发事件,并在另一个组件中监听并响应该事件。以下是自定义事件的使用方法:

    1. 定义一个触发事件的组件:
    1. <template>
    2. <button @click="notify">触发事件</button>
    3. </template>
    4. <script>
    5. export default {
    6. methods: {
    7. notify() {
    8. this.$emit('custom-event', payload);
    9. }
    10. }
    11. };
    12. </script>
    1. 监听并响应事件的组件:
    1. <template>
    2. <div>
    3. <p>接收到的消息: {{ message }}p>
    4. div>
    5. template>
    6. <script>
    7. export default {
    8. data() {
    9. return {
    10. message: ''
    11. };
    12. },
    13. mounted() {
    14. this.$on('custom-event', this.handleCustomEvent);
    15. },
    16. methods: {
    17. handleCustomEvent(payload) {
    18. this.message = `收到消息: ${payload}`;
    19. }
    20. }
    21. };
    22. script>

    在上述代码中,使用 $on 方法来在 mounted 钩子中监听名为 custom-event 的自定义事件。在收到事件时,调用相应的处理函数 handleCustomEvent,并更新 message 数据。

    解绑自定义事件

    在Vue.js中,解绑自定义事件可以通过 $off 方法来实现。这个方法用于移除一个或多个事件监听器。以下是解绑自定义事件的几种方法:

    方法一:解绑单个事件监听器

    1. <template>
    2. <button @click="unsubscribe">解绑事件</button>
    3. </template>
    4. <script>
    5. export default {
    6. created() {
    7. this.$on('custom-event', this.handleCustomEvent);
    8. },
    9. methods: {
    10. unsubscribe() {
    11. this.$off('custom-event', this.handleCustomEvent);
    12. },
    13. handleCustomEvent(payload) {
    14. // 处理自定义事件的逻辑
    15. }
    16. }
    17. };
    18. </script>

    在上述代码中,this.$off('custom-event', this.handleCustomEvent) 会解绑组件中的 custom-event 自定义事件的 handleCustomEvent 事件处理函数。

    方法二:解绑所有事件监听器

    1. <template>
    2. <button @click="unsubscribeAll">解绑所有事件button>
    3. template>
    4. <script>
    5. export default {
    6. created() {
    7. this.$on('custom-event', this.handleCustomEvent);
    8. this.$on('another-event', this.handleAnotherEvent);
    9. },
    10. methods: {
    11. unsubscribeAll() {
    12. this.$off();
    13. },
    14. handleCustomEvent(payload) {
    15. // 处理 custom-event 事件的逻辑
    16. },
    17. handleAnotherEvent(payload) {
    18. // 处理 another-event 事件的逻辑
    19. }
    20. }
    21. };
    22. script>

    在上述代码中,this.$off() 会解绑组件中的所有事件监听器,包括 custom-eventanother-event

  • 相关阅读:
    软件测试工作的基本流程详解
    深度学习——特征点检测和目标检测
    em与rem的区别
    julia笔记:函数
    Glitch free 无毛刺时钟切换电路,时钟无缝切换,时钟无毛刺切换技术
    独享IP vs. 共享IP:哪种更适合你?
    Python实验项目7 :tkinter GUI编程
    【Azure Developer】使用 Microsoft Authentication Libraries (MSAL) 如何来获取Token呢 (通过用户名和密码方式获取Access Token)
    Maven私服创建--Nexus
    【Spring 篇】SpringMVC的请求:舞台上的开端
  • 原文地址:https://blog.csdn.net/qq_56043285/article/details/133036561