因为v2使用公共配置时一般绑定在原型上无论是否使用都在每一个组件的this链上,这样的设计不太友好,v3提供了专门公共数据配置的方式: globalProperties getCurrentInstance
main.js文件中:
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
app.config.globalProperties.$demo= "hello world"
app.config.globalProperties.variable = 99999999
app.mount('#app')
在组件中使用:
{{re.proxy.$demo}}
{{re.proxy.variable}}
vite脚手架中:
vite.config.js文件中:
import {
defineConfig
} from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()],
server: {
// port:"",
// host
proxy: {
'/api': {
target: 'http://127.0.0.1:7001', // 代理的目标地址
rewrite: (path) => path.replace(/^\/api/, '/'), // 路径重写
changeOrigin: true,
// secure: true, // target是否https接口
// ws: true, // target是否代理websockets
}
}
}
})
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')
在组件中使用:
1、现在终端输入 npm i axios 下载axios
然后再main.js中:
import { createApp } from 'vue'
import App from './App.vue'
import router from "./router/index.js"
createApp(App).use(router).mount('#app')
在路由文件router下配置:
//路由文件
import { createRouter, createWebHistory } from 'vue-router'
const routes = [
{
path: '/',
name: 'home',
component: () => import('../views/home.vue'),
//独享守卫
beforeEnter(to,from,next){
next()
}
},
]
const router = createRouter({
history: createWebHistory(),
routes
})
//全局守卫配置
router.beforeEach((to,from,next)=>{
//进行业务操作
next()
})
router.beforeResolve((to,from,next)=>{
//进行业务操作
next()
})
router.afterEach((to,from)=>{
//进行业务操作
})
export default router
组件中使用:
import {onBeforeRouteLeave,useRouter,useRoute} from "vue-router"
let router=useRouter()
let fn=()=>{
let route=useRoute()
console.log(route.query)
router.push({path:"/home",query:{id:123}})
}
//组件内的守卫钩子
onBeforeRouteLeave((to,from,next)=>{
console.log(66666,"离开")
next()
})
pinia中文网网址:https://pinia.web3doc.top/
下载:
npm install pinia
在main.js文件中配置:
import { createApp } from 'vue'
import App from './App.vue'
import {createPinia} from "pinia"
createApp(App).use(createPinia()).mount('#app')
在仓库文件中使用:
import {defineStore} from "pinia"
export const useStore = defineStore("组件的名字",{
state: () => {
return {
}
}
})