vue3.0 mounts global api and global custom methods or Provide, inject global variables and methods

1. Global API

1. Create a new api file
api.js

const BASE_URL = import.meta.env.VITE_BASE_API: // 环境变量
export const url = {
  LOGIN: `${BASE_URL}/api/login`, // 登录
  LOGIN_CODE: `${BASE_URL}/api/captchaImage`, // 获取验证码
}
2. Mount it globally in main.js
main.js

import { createApp } from 'vue'
import App from './App.vue';
import router from './router';
import store from './store';
import { url } from './services/api'; // 导入封装的api

const app = createApp(App)
app.config.globalProperties.$http = url; // 挂载全局
app.use(router).use(store).mount('#app')
3. Use in components
login.vue

<script setup>
import { request } from '../../utils/request'; // 封装的axios
const globalProperties = getCurrentInstance().appContext.config.globalProperties; // 获取全局挂载
const http = globalProperties.$http;
console.log(http);
// 获取验证码
const getCode = async () => {
  await request(http.LOGIN_CODE, 'get')
    .then((res) => {
      if(res.code === 200) {
        codeImg.value = res.data.img;
        captcha.value = res.data.captcha;
        uuid.value = res.data.uuid;
      }
    })
    .catch(() => {

    })
    .finally(() => {
      
    })
}
</script>
4. The results printed by console.log(http) are as follows:

insert image description here

Second, the custom global method

1. Create a new modal.js file
modal.js

/**
 * 
 * 提示弹窗
 */
export const toast = function (msg, duration) {
  duration = isNaN(duration) ? 2000 : duration; // 动画延迟
  var m = document.createElement('div');
  m.innerHTML = msg; // 提示语
  m.style.cssText = "min-width: 150px; padding: 10px;opacity: 0.7;color: rgb(255, 255, 255);text-align: center;border-radius: 5px;position: fixed;top: 50%;left: 50%;z-index: 999999;background: rgb(42, 168, 55);font-size: 12px;";
  document.body.appendChild(m);
  if(timer) {
    clearTimeout(timer)
  }
  var timer = setTimeout(function () {
    var d = 0.5;
    m.style.webkitTransition = '-webkit-transform ' + d + 's ease-in, opacity ' + d + 's ease-in';
    m.style.opacity = '0';
    if(cssTimer) {
      clearTimeout(cssTimer)
    }
    var cssTimer = setTimeout(function () {
      document.body.removeChild(m)
    }, d * 1000);
  }, duration);
}
export default toast
2. Mount it globally in main.js
main.js

import { createApp } from 'vue'
import App from './App.vue';
import router from './router';
import store from './store';
import { url } from './services/api'; // 导入封装的api
import toast from './utils/modal';

const app = createApp(App)
app.config.globalProperties.$http = url; // 挂载全局
app.config.globalProperties.$toast = toast; // 挂载全局自定义弹窗
app.use(router).use(store).mount('#app')
3. Use in components
login.vue

<script setup>
import { request } from '../../utils/request';
const globalProperties = getCurrentInstance().appContext.config.globalProperties; // 获取全局挂载
const http = globalProperties.$http;
const toast = globalProperties.$toast;
console.log(toast);
// 登录
const handleLogin = async (username, password, captcha, uuid) => {
  logging.value = true;
  await request(http.LOGIN, 'post', {
    username,
    password: Base64.encode(username + '8' + password),
    captcha,
    uuid
  })
    .then((res) => {
      console.log(res);
      if(res.code == 200) {
        toast("登录成功!");
        router.push('/home');
      }
    })
    .catch(() => {
      
    })
    .finally(() => {
      logging.value = false;
    })
}
</script>
4. The console.log(toast) print result is as follows:

insert image description here

5. Inadvertently see the article of the big guy: https://blog.csdn.net/Boale_H/article/details/118857338 There is another way:

main.js

import { createApp } from 'vue';
import App from './App.vue';
import router from './router/index.js';
import store from './store';
import { url } from './services/api.js'; // 导入封装的api
import {changeSize} from './utils/common.js';
import toast from './utils/modal.js';
import antd from 'ant-design-vue';
import 'ant-design-vue/dist/antd.less';
import './assets/common/style.less';
import 'animate.css';

changeSize()
const app = createApp(App)
app.config.globalProperties.$http = url; // 挂载全局
app.provide('toast', toast); // 调用 provide 来定义每个property(toast)
app.use(antd).use(router).use(store).mount('#app')

home.view

<script setup>
import { inject } from 'vue';
const toast = inject('toast');
toast("你好,陌生人!");
</script>
6. Custom components can be played like this, and global api variables can also be used. It is too troublesome to mount too much code. Provide dependencies in app.vue
App.vue
import { onMounted,provide } from "vue";
import { url } from './services/api.js'; // 导入封装的api
provide('url',url)
7. Inject dependencies into components
login.vue
const url = inject('url')
// 获取验证码
const getCode = async () => {
  await request(url.LOGIN_CODE, 'get')
    .then((res) => {
        codeImg.value = res.img;
        captcha.value = res.captcha;
        uuid.value = res.uuid;
    })
    .catch(() => {

    })
    .finally(() => {
      
    })
}
8. Official document: https://v3.cn.vuejs.org/guide/composition-api-provide-inject.html#%E4%BD%BF%E7%94%A8-provide

In 2022, work hard to be yourself!

Guess you like

Origin blog.csdn.net/agua001/article/details/122835808