Front-end notes (4) Vue3 global properties app.config.globalProperties use cases

Vue3 global properties app.config.globalProperties use case

1 Introduction

I have been learning Vue3 for about a month, and I will record the little knowledge points in my learning.
First of all, many students have not found the real official documentation of Vue3. The Vue3 documentation website,
Vue3 official website documentation,
and Vue3API documentation are given below.

2 app.config.globalProperties usage

Official explanation: An object used to register a global property that can be accessed by all component instances in the application.

Case:
First there is a method to request the backend interface

export function listByDictTypeCode(dictTypeCode: string): AxiosPromise<DictData[]> {
    
    
    return request({
    
    
        url: '/dict/data/dictTypeCode/' + dictTypeCode,
        method: 'get'
    });
}

Set app.config.globalPropertie in main.ts file

import {
    
    createApp} from 'vue'
import ElementPlus from 'element-plus';
import 'element-plus/dist/index.css'
import App from './App.vue'
import router from './router'
import Pagination from '@/components/Pagination/index.vue';
//引入请求接口的方法
import {
    
     listByDictTypeCode } from '@/api/system/dictData';

const app = createApp(App);

//全局方法
app.config.globalProperties.$listByDictTypeCode = listByDictTypeCode;

app.component('Pagination', Pagination)
app.use(router);
app.use(ElementPlus);
app.mount('#app');

Use getCurrentInstance() in the Vue file and call the method defined above through proxy.$listByDictTypeCode

A lot of other code is omitted here, only the code that shows the use of globalProperties is given

<template>
    <el-tree-select
          v-model="dataState.selectValue"
          :data="dataState.dictDataList"
          :props="defaultProps"
          check-strictly
          :render-after-expand="false"
      />
    </el-form-item>
<template>

<script setup lang="ts">
import {
    
    nextTick, reactive, ref, getCurrentInstance} from "vue";
const {
    
     proxy }: any = getCurrentInstance();

const defaultProps = {
    
    
  label: 'name',
  value: 'id',
  children: 'children'
}

const dataState = reactive({
    
    
  selectValue: '',
  dictTypeCode: '',
  dictDataList: [] as DictData[]
});

function handleQuery() {
    
    
  proxy.$listByDictTypeCode(dataState.dictTypeCode).then((data: any) => {
    
    
    console.log(data.data)
    dataState.dictDataList = data.data;
  })
}
</script>

Insert image description here

Guess you like

Origin blog.csdn.net/winterking3/article/details/126118712