vue3+setup+ts使用全局方法

1,641 阅读1分钟

一个公共方法:myalert

src/utils/myalert.ts

const myalert = (val:any):void => {
  alert(val);
};
export default { myalert };

方法1:app.config.globalProperties

main.js

import { createApp } from 'vue'
const app = createApp(App)

import myAlert from "./utils/myAlert.js"
// 注册写法一
app.config.globalProperties.$myAlert = myAlert.myalert
// 注册写法二
// app.config.globalProperties.$myAlert = myAlert

app.use(...) 
app.mount('#app')

要使用myalert方法的组件

<template>
    <button @click="al(123)">jaijai</button>
</template>
<script setup lang="ts">
import { getCurrentInstance } from "vue";
// 1.结构赋值
const { proxy } = getCurrentInstance();
// 2.直接赋值
// const proxy = getCurrentInstance()?.proxy
const al = (val: any) => {  
    // 公共方法的使用
    // 前面注册写法一的使用方法
    proxy?.$myAlert(val);
    // 前面注册写法二的使用方法
    // proxy?.$myAlert.myalert(val);
};
</script>

方法2:app.mixin

main.js

import { createApp } from 'vue'
const app = createApp(App)

import myAlert from "./utils/myAlert.js"
app.mixin({
    methods: {
      $myalert: myAlert.myalert 
    }
  })
app.use(...) 
app.mount('#app')

要使用myalert方法的组件

<template>
    <button @click="al(123)">jaijai</button>
</template>
<script setup lang="ts">
import { getCurrentInstance } from "vue";
// 1.结构赋值
const { proxy } = getCurrentInstance();
// 2.直接赋值
// const proxy = getCurrentInstance()?.proxy
const al = (val: any) => {  
    // 公共方法的使用 
    proxy?.$myalert(val); 
};
</script>

方法3:provide/inject

main.js

import { createApp } from 'vue'
const app = createApp(App)

import myAlert from "./utils/myAlert.js"
app.provide('$myAlert', myAlert)

app.use(...) 
app.mount('#app')

要使用myalert方法的组件

<template>
    <button @click="al(123)">jaijai</button>
</template>
<script setup lang="ts">
import { getCurrentInstance, inject } from "vue";
// 1.结构赋值
const { proxy } = getCurrentInstance();
// 2.直接赋值
// const proxy = getCurrentInstance()?.proxy
const $myAlert = inject("$myAlert");
const al = (val: any) => {  
    // 公共方法的使用 
    proxy?.$myalert(val); 
};
</script>