在vue2中,我们知道vue2.x是使用Vue.prototype.$xxxx=xxx
来定义全局变量,然后通过this.$xxx
来获取全局变量。
vue3是没有this的所以我们不能用vue2的方法
我们需要在main.js来创建全局变量
import { useDict } from '@/utils/dict'
// 全局方法挂载
app.config.globalProperties.useDict = useDict
//当然我们也可以自定义变量
app.config.globalProperties.count = 0
在组件如何读取全局变量:
我们需要从vue中引入getCurrentInstance
import { getCurrentInstance } from "vue";
const { proxy } = getCurrentInstance();
console.log(proxy.count );//控制台可以看到输出了
如果我们想用watch来监听全局变量是不可以的,因为全局变量不是响应式的所以是不会触发watch监听器的
vue3你可以使用pinia仓库