• 自定义事件


    一、绑定事件:

    定义:子给父传递数据:通过父组件给子组件绑定一个自定义事件。

     @或v-on

    App.vue代码:

    <Student @sendName="getName"/> 

    Student是子组件,sendName:事件名称,getName:回调函数

    Student.vue代码

    使用this.$emit调用,第一个参数为:事件名称,第二个参数:传递的数据

    1. methods: {
    2. pressBtn() {
    3. // 调用自定义事件
    4. this.$emit('sendName',this.name); 
    5. }
    6. },

    子组件添加ref

    给子组件添加ref=”student”,用$on的方式添加,第一个参数:名称,第二个参数:回调函数。
     

    1. mounted() {
    2. this.$refs.student.$on("sendName",this.getName);
    3. }

    注意:

    1:如果子组件调用原生事件 需要添加native,否则会当成自定义组件,如:

    @click.native="show"

    2:$once,只执行一次。

    二、事件解绑:

    解绑一个事件

    this.$off(‘xxxx’ )    xxxx:事件名称

    解绑多个事件

     this.$off([‘x1’,’x2’])   使用数组的形式。

    解绑所有事件

    this.$off()

    销毁组件实例

    this.$destroy() //销毁了当前Student组件的实例,销毁后所有Student实例的自定义事件全都不奏效。

    案例 

    App.vue

    1. <script>
    2. import Person from './components/Person.vue';
    3. export default {
    4. name:"App",
    5. data(){
    6. return {
    7. title:"2209班",
    8. }
    9. },
    10. methods: {
    11. showName(name) {
    12. console.log("App得到了姓名",name);
    13. },
    14. showAge(age){
    15. console.log("App得到了年龄(this.refs.xxx.$on)",age);
    16. },
    17. show(){
    18. alert("123")
    19. }
    20. },
    21. components: {
    22. Person
    23. },
    24. mounted(){
    25. //第一个参数:自定义事件的名称,第二个参数:自定义事件的回调
    26. //$once 事件只执行一次
    27. this.$refs.person.$on("getAge",this.showAge);
    28. }
    29. }
    30. script>
    31. <style>
    32. style>

    components-Person

    1. <script>
    2. export default{
    3. name:"Person",
    4. data(){
    5. return {
    6. name:"张三",
    7. age:19
    8. }
    9. },
    10. methods:{
    11. sendName(){
    12. // console.log("子组件",this.name);
    13. this.$emit("getName",this.name);
    14. },
    15. sendAge(){
    16. this.$emit("getAge",this.age);
    17. },
    18. offAge(){
    19. console.log("getAge 已解绑")
    20. this.$off("getAge");
    21. },
    22. // 销毁组件实例
    23. mydestory(){
    24. console.log("组件实例已销毁");
    25. this.$destroy();
    26. }
    27. }
    28. }
    29. script>
    30. <style>
    31. style>

    main.js

    1. import Vue from 'vue'
    2. import App from './App.vue'
    3. Vue.config.productionTip = false
    4. new Vue({
    5. render: h => h(App),
    6. }).$mount('#app')

  • 相关阅读:
    LiteFlow 开源编排规则引擎
    线扫相机的使用
    COLMAP简明教程 重建 转化深度图 导出相机参数 导入相机参数 命令行
    Spring Boot概述
    故障排除指南:解决 Kibana Discover 加载中的 6 个常见问题
    JVM的类的生命周期
    D358周赛复盘:哈希表模拟⭐⭐+链表乘法翻倍运算(先反转)⭐⭐⭐
    面试官:说说React-SSR的原理
    【JAVA入门】JUnit单元测试、类加载器、反射、注解
    vim 配置C/C++单文件无参数编译运行
  • 原文地址:https://blog.csdn.net/m0_59359854/article/details/126345245