在 uniapp 的 Vue3 项目中,通过 this.$
方式引用方法需结合全局属性和 Composition API 的特性实现。以下是具体方案及注意事项:
一、全局方法挂载(适用于自定义方法或工具类)
-
在
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
等)
-
通过
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 }
}
}
三、注意事项
-
Vue3 中
this
的限制- 在
setup
函数内无法直接使用this
,需通过getCurrentInstance().proxy
或ref
变量替代。 - 全局变量需通过
app.config.globalProperties
显式声明,而非直接挂载到 Vue 原型链。
- 在
-
第三方库兼容性
- 部分 Vue2 插件需适配 Vue3 的全局 API,例如事件总线(
this.$on
/this.$emit
)需改用mitt
等库实现
- 部分 Vue2 插件需适配 Vue3 的全局 API,例如事件总线(
四、完整示例(全局方法 + 组件调用)
// 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 规范