首页 前端知识 vue-head 插件设置浏览器顶部 favicon 图标 - 动态管理 html 文档头部标签内容

vue-head 插件设置浏览器顶部 favicon 图标 - 动态管理 html 文档头部标签内容

2024-05-28 09:05:31 前端知识 前端哥 594 983 我要收藏

目录

  • 需求
  • 实现1
    • 1. 安装插件
    • 2. 项目内 main.js 引入
    • 3. vue页面使用
  • 实现2
  • 其他

需求

vue项目中浏览器页面顶部图标可配置

在这里插入图片描述

实现1

使用 vue-head 插件实现

  • vue-head 插件可实现 html 文档中 head 标签中的内容动态配置(npm 官网 vue-head 插件)

1. 安装插件

npm install vue-head --save
复制

2. 项目内 main.js 引入

import VueHead from 'vue-head'
Vue.use(VueHead)
复制

3. vue页面使用

我所有页面(所有路由)都用这个图标,因为 vue 项目是 SPA,只有一个页面,所以我在 APP.vue 使用
如果有不同路由展示不同图标的需求,则可在不同路由对应的 vue 文件中单独配置 head。

<script>
import { mapGetters } from "vuex";
export default {
name: "app",
components: {},
provide() {
return {
reload: this.reload
};
},
data() {
return {
// ...
};
},
computed: {
...mapGetters(["theme", 'userInfo', 'sysConfigData']),
// ...
},
methods: {
// ...
},
mounted() {
// ...
},
// 【主要代码】head 中每一个属性其实代表的就是 head 标签中的 mete标签、link标签、script标签、style标签等等……
head: {
meta: [
// { name: 'application-name', content: 'Name of my application' },
// { name: 'description', content: 'A description of the page', id: 'desc' }, // id to replace intead of create element
// // ...
// // Twitter
// { name: 'twitter:title', content: 'Content Title' },
// // with shorthand
// { n: 'twitter:description', c: 'Content description less than 200 characters'},
// // ...
// // Google+ / Schema.org
// { itemprop: 'name', content: 'Content Title' },
// { itemprop: 'description', content: 'Content Title' },
// // ...
// // Facebook / Open Graph
// { property: 'fb:app_id', content: '123456789' },
// { property: 'og:title', content: 'Content Title' },
// // with shorthand
// { p: 'og:image', c: 'https://example.com/image.jpg' },
// // ...
],
// 【主要代码】不能使用 this 会报错 undefined
// link: [
// { rel: 'icon', href: require('@/assets/favicon.png'), sizes: '16x16', type: 'image/png' }
// ],
// 【主要代码】使用this
link() {
return [
{ rel: 'icon', href: require(`@/assets/${this.sysConfigData['mon.sys.favicon']}.png`), sizes: '16x16', type: 'image/png' }
]
},
script: [
// { type: 'text/javascript', src: 'cdn/to/script.js', async: true, body: true}, // Insert in body
// // with shorthand
// { t: 'application/ld+json', i: '{ "@context": "http://schema.org" }' },
// // ...
],
style: [
// { type: 'text/css', inner: 'body { background-color: #000; color: #fff}', undo: false },
// // ...
]
}
};
</script>
复制

实现2

使用原生 js 给图标标签 link 的图片地址 href 重新赋值

<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<!-- 或 -->
<link id="favicon" rel="icon" href="<%= BASE_URL %>favicon.ico">
复制
// 新的图标地址 iconUrl
document.querySelectAll("link[rel*='icon']").forEach(item => {
item.href = iconUrl; // 赋值新的图标地址 iconUrl
})
// 或
const dom = document.getElementById("favicon")
dom && (dom.href = iconUrl) // 赋值新的图标地址 iconUrl
复制

其他

npm 官网 vue-head

转载请注明出处或者链接地址:https://www.qianduange.cn//article/9878.html
标签
评论
还可以输入200
共0条数据,当前/页
发布的文章

JQuery中的load()、$

2024-05-10 08:05:15

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!