一、 vue3设置全局变量
1.1 方法一 config.globalPropertie
// 之前 (Vue 2.x)
Vue.prototype.$http = () => {}
// 之后 (Vue 3.x)
const app = createApp({})
app.config.globalProperties.$http = () => {}
1.2 方法二 Provide / Inject
vue3新的 provide/inject 功能可以穿透多层组件,实现数据从父组件传递到子组件。
将全局变量放在根组件的 provide 中,这样所有的组件都能使用到这个变量。
如果变量是响应式的,就需要在 provide 的时候使用 ref 或者 reactive 包装变量。
二、 v-bind修饰符
v-bind修饰符主要是为属性进行操作,用来分别有如下:
- async
- prop
- camel
2.1 async
能对props进行一个双向绑定
//父组件
<comp :myMessage.sync="bar"></comp>
//子组件
this.$emit('update:myMessage',params);
以上方法相当于以下的简写:
//父亲组件
<comp :myMessage="bar" @update:myMessage="func"></comp>
func(e){
this.bar = e;
}
//子组件js
func2(){
this.$emit('update:myMessage',params);
}
使用async需要注意以下两点:
- 使用
sync的时候,子组件传递的事件名格式必须为update:value,其中value必须与子组件中props中声明的名称完全一致 - 注意带有
.sync修饰符的v-bind不能和表达式一起使用 - 将
v-bind.sync用在一个字面量的对象上,例如v-bind.sync=”{ title: doc.title }”,是无法正常工作的
2.2 props
设置自定义标签属性,避免暴露数据,防止污染HTML结构
<input id="uid" title="title1" value="1" :index.prop="index">
2.3 camel
将命名变为驼峰命名法,如将 view-Box属性名转换为 viewBox
<svg :viewBox="viewBox"></svg>
三、vue3 实现刷新当前页面
3.1 App.vue
<template>
<route-view v-slot="{component}" v-if="isRouteActive">
<keep-alive>
<Component :is="component">
</keep-alive>
</route-view>
</template>
import { provide, ref, nextTick } from 'vue'
const isRouteActive = ref(true);
const reload = ()=>{
isRouteActive.value = false;
nextTick(()=>{
isRouteActive.value = true;
})
}
provide('reload', reload)
3.2 需要刷新的页面
import { inject } from 'vue'
consr reload = inject('inject');
// 下面这行代码写在你需要reload的地方
reload();
四、vue解决VUE项目更新后需要客户手动刷新浏览器问题
4.1 打包时自动编译版本到version.json文件(版本换成时间)
vue.config.js文件添加,每次打包后自动获取编译时间写入版本文件
// 解决VUE项目更新后需要客户手动刷新浏览器问题start
let test = require('./public/version.json') || [];
let fs = require('fs');
// 获取当前时间戳
//const time = setTime(new Date(version));
if(process.env.NODE_ENV === "production"){
let shijianchuo = parseInt(new Date().getTime()) + '';
test={
'version': shijianchuo
};
fs.writeFile('./public/version.json', JSON.stringify(test), () => {
console.log('新版本号生成成功');
});
}
// 解决VUE项目更新后需要客户手动刷新浏览器问题end
4.2 app.vue获取版本号进行更新
import {onMounted} from 'vue'
import axios from 'axios'
const getVerson = () => {
if (process.env.NODE_ENV === "development") return;
axios.get("/public/version.json",{params:{data: parseInt(new Date().getTime()) + ''}})
.then(res => {
console.log("查询版本")
let lastVersion=res.data.version
console.log('lastVersion',lastVersion)
if(localStorage.version==undefined){
localStorage.setItem("version", lastVersion)
}else{
if(localStorage.version!=lastVersion){
localStorage.removeItem("version")
router.go(0)
}
}
})
}
onMounted(()=>{
getVerson()
})