Vue3中的公共数据配置globalProperties getCurrentInstance、网络代理配置

目录

公共数据配置

globalProperties

getCurrentInstance

案例:

Vue3 网络代理配置axios

main.js中

config.js中进行代理配置proxy

 组件的代码app.vue


公共数据配置

因为v2使用公共配置时一般绑定在原型上无论是否使用都在每一个组件的this链上,这样的设计不太友好,v3提供了专门公共数据配置的方式: globalPropertiesgetCurrentInstance

globalProperties

在vue2中我们将公共数据直接写入Vue.prototype中,例如:

vue2中axios的公共数据配置即事件代理http://t.csdn.cn/Pq4FE

所以在vue3中提供了globalProperties函数

用法:const app=createApp(App)
          app.config.globalProperties.$test="这是公共数据"  ($test为自定义属性名)                                  app.mount('#app')

getCurrentInstance

1、getCurrentInstance()获取当前组件实例对象
2、当前组件的实例对象解构的proxy对象中就有$test(自定义属性名)   
3、注意点是这个函数要在组件钩子中使用,不要在普通函数中使用

案例:

main.js文件

//main.js
import { createApp } from 'vue'
import App from './App.vue'

const app=createApp(App)
app.config.globalProperties.$test="这是公共数据" 

app.mount('#app')

组件






控制台打印:

说明成功接收到了公共数据

Vue3 网络代理配置axios

main.js中

1、引入axios

2、配置axios的基础路径(主要为了设置API

3、再配置公共数据引入axios

import { createApp } from 'vue'
import App from './App.vue'

import axios from "axios"

axios.defaults.baseURL="http://127.0.0.1:5173/api1" //设置axios的基本路径+自己设定的api

const app=createApp(App)
app.config.globalProperties.$axios=axios //将axios设置为公共数据,这样在使用时就不必在每个组件文件中引用


app.mount('#app')

config.js中进行代理配置proxy

如果是invite环境下则为

import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  
  server: {
  		
  		proxy: {
  			'/api1': {
  				target: 'http://127.0.0.1:7001', // 代理的目标地址,我这里是用的egg的地址
  				rewrite: (path) => path.replace(/^\/api1/, '/'), // 路径重写
  				changeOrigin: true,
  				// secure: true, // target是否https接口
  				// ws: true, // target是否代理websockets               
  			}
  		}
  	},
	
})

如果是webpack环境则可以参考我再vue2中的axios配置,基本相同http://t.csdn.cn/yLlUH

 组件的代码app.vue






已知后端的数据为

Vue3中的公共数据配置globalProperties getCurrentInstance、网络代理配置_第1张图片

界面效果 和控台打印:

Vue3中的公共数据配置globalProperties getCurrentInstance、网络代理配置_第2张图片Vue3中的公共数据配置globalProperties getCurrentInstance、网络代理配置_第3张图片说明成功请求到了后端的数据,并展现到了界面上

你可能感兴趣的:(Vue,vue.js,前端,javascript)