Vue3如何绑定全局方法和变量

Vue 2 中 Vue.prototype绑定全局方法,此写法在 Vue 3 已经不存在了。与任何全局的东西一样,应该谨慎使用。

Vue3使用provide/inject 或者app.config.globalProperties进行绑定

如果全局属性与组件自己的属性冲突,组件自己的属性将具有更高的优先级。

 

一、provide/inject方法
 1. test.js文件中定义需要绑定的方法和变量
// test.js
export const testFn = () => {
  console.log('testFn---');
}
export const testName = '哎呀'
 2. main.js文件中引入绑定的方法和变量 ,并通过app.provide注入全局方法和变量
// main.js
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import { testFn1, testFn, testName, testName1 } from './utils/test.js';

const app = createApp(App);

// 绑定全局方法
app.provide('testFn', testFn)

// 绑定全局变量
app.provide('testName', testName)

app.use(router);
app.mount('#app');
3. about.vue文件中通过inject获取全局方法和变量 
<!-- about.vue -->
<template>
  <div>about</div>
</template>
<script setup>
import { inject } from 'vue'
const testFn = inject('testFn')
testFn()

const testName = inject('testName')
console.log('testName--', testName);

</script>

二、app.config.globalProperties
 1. test.js文件中定义需要绑定的方法和变量
// test.js
export const testFn1 = () => {
  console.log('testFn1---');
}

export const testName1 = '哎呀呀呀'
 2. main.js文件中引入绑定的方法和变量 ,并通过app.provide注入全局方法和变量
// main.js
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import { testFn1, testFn, testName, testName1 } from './utils/test.js';

const app = createApp(App);

// 绑定全局方法
app.config.globalProperties.testFn1 = testFn1

// 绑定全局变量
app.config.globalProperties['testName1'] = testName1

app.use(router);
app.mount('#app');
3. about.vue文件中通过inject获取全局方法和变量 
<!-- about.vue -->
<template>
  <div>about</div>
</template>
<script setup>
import { getCurrentInstance } from 'vue'

const { proxy } = getCurrentInstance()
proxy.testFn1()
console.log('testName1--', proxy.testName1);

</script>

做个记录,如有不足,欢迎补充。

不要忽视你达成的每个小目标,它是你前进路上的垫脚石。冲!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值