Write the Code. Change the World.

5月 05

vue3 出来那么久了。以前的项目 vue2 也该更更更了。新项目那必须得 vue3 了。不过,有些关键的写法,会有些不同。一点点的来。

globalProperties

在 vue2,想定义一个全局的属性(方法或变量),只需要定义在 Vue.prototype 上就可以。然后在 template 中可以直接使用,在 script 中,通过 this 来访问使用。

到了 vue3 这里,就不一样了。这些方法和属性定义在 globalProperties, 就是 app.config.globalProperties 上。

比如:

import App from './App'

import {
    createSSRApp
} from 'vue'

const app = createSSRApp(App)

app.config.globalProperties.$test = (value) => {
    console.log('test ' + value)
}

vue3 是干掉 this 的。使用的时候这样。

import { onMounted, getCurrentInstance } from 'vue'

onMounted(() => {
    const { proxy,  ctx } = getCurrentInstance()
    proxy.$test('全局调用')
})

template 中,则可以直接使用。 getCurrentInstance 还有一个输出 ctx,这个和 vue2 时候的 this 一个样。