让uniapp vue3 通过this.$方式直接引用方法的实现方式

在 uniapp 的 Vue3 项目中,通过 this.$ 方式引用方法需结合全局属性和 Composition API 的特性实现。以下是具体方案及注意事项:


一、全局方法挂载(适用于自定义方法或工具类)

  1. 在 main.js 中配置全局属性
    使用 app.config.globalProperties 挂载全局方法或变量:

import { createSSRApp } from 'vue'
import App from './App'

export function createApp() {
  const app = createSSRApp(App)
  // 挂载全局方法
  app.config.globalProperties.$formatTime = (timestamp) => {
    return new Date(timestamp).toLocaleString()
  }
  return { app }
}

        2. 组件中通过 getCurrentInstance 调用

在 Vue3 的 setup 函数中无法直接使用 this,需通过 getCurrentInstance 获取上下文:

import { getCurrentInstance } from 'vue'

export default {
  setup() {
    const { proxy } = getCurrentInstance()
    // 调用全局方法
    const formattedTime = proxy.$formatTime(Date.now())
    return { formattedTime }
  }
}

‌       3. 模板或 Options API 中直接使用 this.$
若使用 Options API 或在模板中,可直接通过 this.$xxx 调用:

export default {
  methods: {
    showTime() {
      console.log(this.$formatTime(Date.now()))
    }
  }
}

二、组件引用(如 uni-popup 等)

  1. 通过 ref 绑定组件
    在模板中声明 ref 属性:

<uni-popup ref="messagePopup" type="message">
  <uni-popup-message :type="msgType" :message="messageText" />
</uni-popup>

‌        2. 在 setup 中操作组件实例
使用 ref 变量和 setup 函数控制组件

import { ref } from 'vue'

export default {
  setup() {
    const messagePopup = ref(null)
    // 调用组件方法
    const openPopup = () => {
      messagePopup.value?.open()
    }
    return { messagePopup, openPopup }
  }
}

三、注意事项

  1. Vue3 中 this 的限制

    • 在 setup 函数内无法直接使用 this,需通过 getCurrentInstance().proxy 或 ref 变量替代‌。
    • 全局变量需通过 app.config.globalProperties 显式声明,而非直接挂载到 Vue 原型链‌。
  2. 第三方库兼容性

    • 部分 Vue2 插件需适配 Vue3 的全局 API,例如事件总线(this.$on/this.$emit)需改用 mitt 等库实现‌

四、完整示例(全局方法 + 组件调用)

// main.js
import { createSSRApp } from 'vue'
import App from './App'

export function createApp() {
  const app = createSSRApp(App)
  app.config.globalProperties.$showToast = (message) => {
    uni.showToast({ title: message, icon: 'none' })
  }
  return { app }
}

// 组件内
import { ref, getCurrentInstance } from 'vue'

export default {
  setup() {
    const { proxy } = getCurrentInstance()
    const messagePopup = ref(null)

    const handleClick = () => {
      proxy.$showToast('操作成功') // 调用全局方法
      messagePopup.value?.open()  // 调用组件方法
    }

    return { messagePopup, handleClick }
  }
}

通过上述方案,可灵活实现 this.$ 风格的全局方法调用及组件操作,同时遵循 Vue3 的 Composition API 规范‌

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值