• 自定义事件的使用


    绑定自定义事件

    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

  • 相关阅读:
    突发,富士康被调查!苹果正将更多订单交给中国代工厂
    【LVGL】ANIM(动画)时间线学习
    java spring cloud 企业工程管理系统源码+二次开发+定制化服务
    孙子兵法_00000
    SpringSecurity---PasswordEncoder
    【Docker Compose】Docker Compose 的安装,使用以及实现微服务集群的部署
    Lesson 2 Breakfast or lunch?
    [algorithm] 二叉树的DFS与BFS算法 (Java) -- 痛定思痛 彻底搞懂
    搭建好自己的PyPi服务器后怎么使用
    Java中的迭代器设计模式[85]
  • 原文地址:https://blog.csdn.net/qq_56043285/article/details/133036561