前端笔记(4) Vue3 全局属性 app.config.globalProperties 使用案例

Vue3 全局属性 app.config.globalProperties 使用案例

1 前言

学习Vue3有个把月了,记录下学习中的小知识点。
首先很多同学还没找到Vue3真正的官方文档,下面给出Vue3的文档网站
Vue3官网文档
Vue3API文档

2 app.config.globalProperties使用

官方解释:一个用于注册能够被应用内所有组件实例访问到的全局 property 的对象。

案例:
首先有一个请求后端接口的方法

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

在main.ts文件中设置app.config.globalPropertie

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');

在Vue文件中使用getCurrentInstance(),通过proxy.$listByDictTypeCode就可以调用上面定义的方法

这里省略了很多别的代码,只给了能够表明globalProperties使用的代码

<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>

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/winterking3/article/details/126118712