vue3 公共数据配置以及网络配置

694 阅读2分钟

公共数据配置

vue2

vue2使用公共配置时一般绑定在vue实例的原型上,组件实例的原型对象是指向vue实例的原型,所以组件中可以通过this访问到绑定在原型链的公共配置。

image.png

//main.js
// 请求到的后端服务器数据的公共网址
Vue.prototype.$staticurl='http://localhost:7001'

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')

这样无论是否使用都在每一个组件的原型链上,这样的设计不太友好,vue3 提供了专门公共数据配置的方式: globalProperties 和getCurrentInstance

vue3

//main.js
const app=createApp(App)
app.config.globalProperties.$axios=axios

在组件中钩子中用getCurrentInstance()获取当前组件实例对象相当于vue2 组件中的this。

需要注意的是getCurrentInstance()这个函数必须要在组件钩子中使用,不要在普通函数中使用,普通函数中getCurrentInstance()得到的是null

//组件内部
<script setup>
	import {onBeforeMount,getCurrentInstance} from "vue"
	 const { proxy } = getCurrentInstance();
         //正常使用:语法糖script脚本环境默认为setup钩子函数的内部运行环境
         //当前组件的实例对象解构的proxy对象,普通函数可以用proxy
	 
	 onBeforeMount(()=>{
	 	console.log(getCurrentInstance());
                //正常使用:组件钩子函数
	 })

    let fn=()=>{
        console.log(getCurrentInstance())
        //错误使用:获取null,普通自定义函数不是组件钩子函数
        proxy.$axios(path:'/test')
        //正常使用,当前组件的实例对象解构的proxy对象中就有$axios
    }
</script>

普通函数中获取当前组件的实例对象需要用解构的proxy对象

网络配置

引入网络请求插件

npm i axios  下载到项目中

引入网络请求库可以在每个组件内部使用import axios from 'axios'

也可以在main.js中将其配置在公共配置中

import { createApp } from 'vue'

import App from './App.vue'
import axios from 'axios'

const app=createApp(App);
axios.defaults.baseURL='http://127.0.0.1:5173/api'
app.config.globalProperties.$axios=axios;
app.mount('#app')

需要在挂载前之前设置公共配置,否则组件实例中无法访问

将公共配置封装为一份js文件,在main.js中引入,然后使用app.use引入,和vue.use()同理和做两件事

  • 1.检查插件是否安装,如果安装了就不再安装
  • 2.如果没有安装,那么调用插件的install方法,并传入app实例

app.use(plugin)同理,参数可以是一个对象或者是一个函数

  • 如果参数是一个对象,必须提供 install 方法。
  • 如果参数是一个函数,它自己本身会被作为 install 方法,当外界在 app.use()安装这个插件的时候,install 方法会调用,然后会将 app 作为形参传入install 函数。

当 install 方法被同一个插件多次调用,插件将只会被安装一次,提供 install 方法,只是为了让 app 可以将组件注册到框架里去,使其能够被全局使用。

//   /myhttp/index.js
import axios from "axios";
function packaging(app){
    axios.defaults.baseURL='http://127.0.0.1:5173/api';
    app.config.globalProperties.$axios=axios;   
}
export default packaging;
//要导出该函数
//main.js
import { createApp } from 'vue'

import App from './App.vue'
import myhttp from './myhttp/index.js'
import router from './router/index.js'

const app=createApp(App);
app.use(myhttp);
app.use(router);
app.mount('#app')

main.js中use可以连调因为app.use会返回一个app对象,但是use必须要在mount挂载之前调用,否则组件中无法使用use安装的插件。

app.use(myhttp);
app.use(router);
app.mount('#app')
以上等价于 app.use(myhttp).use(router).mount('#app')

网络配置

vite打包环境

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

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue()],
  server:{
    // port 默认官方配置的5173端口,修改之后在axios的baseURL也要配置同样的端口,可以不用配置
    // host host默认是localhost,可以不用配置
    proxy: {
      '/api': {
        target: 'http://127.0.0.1:7001', 
        // 代理的目标地址
        rewrite: (path) => path.replace(/^\/api/, '/'), 
        // 路径重写
        // path代表传入的pathname比如http://127.0.01:5173/api/test的pathname就是/api路径重写为/test
        changeOrigin: true,
        secure: true, // target是否https接口
        // ws: true, // target是否代理websockets               
      }
    }
  }
})

webpack打包环境

module.exports={
	lintOnSave:false,
	devServer:{
		//port:"8081", //默认可以不用配置
		//host:"localhost", //默认可以不用配置
		proxy:{
			"/":{
				target:"http://127.0.0.1:7001",
				changeOrigin:true,
				pathRewrite:{"^/":""}
			}
		}
	}
}

在组件中使用,做网络请求

<script setup>
  import {onMounted,getCurrentInstance,ref} from 'vue'
  const {proxy}=getCurrentInstance();
  let msg=ref('');
  onMounted(async ()=>{
    let res=await proxy.$axios('/');
    console.log(res);
    msg.value=res.data;
  })
</script>

<template>
  <div class="app">
    <h1>app组件</h1>
    <p>{{msg}}</p>
  </div>
</template>

<style scoped lang='scss'>

</style>

image.png

image.png

let res=await proxy.$axios('/');
因为设置了axios.defaults.baseURL='http://127.0.0.1:5173/api';
所以表示请求的网址是http://127.0.0.1:5173/api/

因为配置了代理,当请求的网址是http://127.0.0.1:5173/api
以/api开头会代理请求http://127.0.0.1:7001