• Vue3父子组件数据传递


    getCurrentInstance方法

    Vue2中,可以通过this来获取当前组件实例;

    Vue3中,在setup中无法通过this获取组件实例,console.log(this)打印出来的值是undefined。

    在Vue3中,getCurrentInstance()可以用来获取当前组件实例。

    let { proxy } = getCurrentInstance();
    
    • 1

    在setup中分别打印下面3个值,结果如下:

    console.log(getCurrentInstance,typeof(getCurrentInstance));
    console.log(getCurrentInstance(),typeof(getCurrentInstance()));
    console.log(proxy,typeof(proxy));
    
    • 1
    • 2
    • 3

    可以看到,getCurrentInstance是一个function方法,getCurrentInstance()是一个对象,proxy也是一个对象。proxy是getCurrentInstance()对象中的一个属性,通过对象的解构赋值方式拿到proxy。

    getCurrentInstance只能在setup或生命周期钩子中使用

    用于线上环境使用方法:

    方法1:

    const instance = getCurrentInstance()
    console.log(instance.appContext.config.globalProperties)
    
    • 1
    • 2

    方法2:

    const { proxy } = getCurrentInstance()  
    
    • 1

    $emit使用方法

    许多Vue模式涉及使用props将数据从父组件传递到子组件。但如果我们需要一个子组件将数据传给它的父组件呢?

    使用 emit,我们可以触发事件并将数据传递到组件的层次结构中。这对下面几种情况很有用,如:

    • 从 input 中发出数据
    • 从 modal 本身内部关闭 modal
    • 父组件响应子组件

    Vue Emit是如何工作的?

    当我们 emit 一个事件时,我们用一个或多个参数调用一个方法:

    • eventName: string - 事件的名称
    • values: any - 通过事件传递的参数

    下面是一个内联 emit的例子,

  • 相关阅读:
    E. Restoring the Permutation
    Python飞行棋游戏源代码,基于socket网络通信的小游戏,可设置多个游戏房间及参与飞行棋游戏的玩家
    Python Opencv实践 - Harris角点检测
    数据挖掘-支持向量机(SVM)+代码实现
    linux,write:xxx has messages disabled 与 Ubuntu多用户同时登录的问题 ubuntu 20.04
    91.(leaflet之家)leaflet态势标绘-进攻方向绘制
    一种使用wireshark快速分析抓包文件amr音频流的思路方法
    HTTP 和 HTTPS
    计算机网络重点概念整理-第四章 网络层【期末复习|考研复习】
    【ELM预测】基于matlab探路者算法优化极限学习机预测(含前后对比)【含Matlab源码 2204期】
  • 原文地址:https://blog.csdn.net/qq_32907491/article/details/133444907