vue3中动态修改浏览器页签favicon以及title
vue3 + element-plus + ts + vite
使用element-plus的上传组件,这里使用的是http-request方式
<el-upload class="common-uploader" action="#" :http-request="httpRequest" :show-file-list="false" accept=".ico" > <span>更换图片</span> </el-upload>
<script lang="ts" setup> import { reactive, ref } from "vue"; import { ElButton, ElForm, ElFormItem, ElMessage, ElUpload, ElInput } from "element-plus"; import { uploadImg, // 上传图片接口 saveFavicon, // 保存接口 getCompany // 获取数据 } from '@/apis' type FormInstance = InstanceType<typeof ElForm>; const ruleFormRef = ref<FormInstance>(); const form = reactive({ faviconUrl: '', webTitle: '' }); const file = ref(""); const httpRequest = async (el: any) => { const temp1 = el.file.name.split("."); const temp = temp1[temp1.length - 1]; if (temp !== "ico") { ElMessage.error("请上传.ico格式的图标"); } else { file.value = el.file; const formdata = new FormData(); formdata.append("file", file.value); const { data: { data, status, message }, } = await uploadImg(formdata); if (status === 200) { form.faviconUrl = data } else { ElMessage.error(message); } } }; const submit = async () => { if (!ruleFormRef.value) return await ruleFormRef.value.validate(async (valid: any) => { if (valid) { const { data: { data, message, status }, } = await saveFavicon(form) if (status == 200) { ElMessage.success('保存成功!') } else { ElMessage.error(message) } } }) } // 获取更新成功后的数据改变favicon、title const getUserCompany = async () => {
const { data: { status, data, message }, } = await getCompany(); if (status === 200) {
// 删除rel为icon的link标签,解决link一直增加导致favicon不能即时刷新的问题 document.head.querySelectorAll("link").forEach(link => { if (link.rel === 'icon') { link.parentNode?.removeChild(link); } }) // 修改浏览器页签title document.title = data.webTitle // 修改浏览器页签图标 const link = document.createElement('link'); link.rel = "icon"; link.href = data.favicon document.head.append(link); } else { ElMessage.warning(message); } }; </script>
本文来自博客园,作者:代码改变世界是吧,转载请注明原文链接:https://www.cnblogs.com/zyh-web/p/17145428.html

浙公网安备 33010602011771号