Vue Cli 3生成的项目如何设置HTML标题

19

目前,使用Vue CLI 3生成项目后的标题为“Vue App”。

如果我通过document.title在created钩子中设置标题,则浏览器仍会在显示通过document.title设置的标题之前闪现“Vue App”。

寻找一种在Vue CLI 3生成的项目中设置HTML标题且不会先闪现默认的“Vue App”标题的方法。

3个回答

19

您可以在 /public/index.html 中静态设置标题。

将其设置为空字符串并在 hook 中保持更新可消除闪烁。


6
更倾向于动态加载。 - xspydr
在 public/index.html 中将标题设置为空就解决了问题。谢谢! - xspydr
@xspydr 嗯,你仍然可以动态设置标题,但是从一个空的默认值开始,而不是错误的值。 - wwerner
2
在我新创建的Vue CLI 4应用程序中,没有“/public/index.html”,所以我不得不创建一个:<!DOCTYPE html><html lang="us"><head><title>My Title</title></head><body><div id="app"></div></body></html> - zett42
2
如果有人需要的话,我想提醒一下,由于某些原因,我删除了默认的 index.html 文件,现在需要恢复默认内容。你可以从 \node_modules\@vue\cli-service\lib\config\index-default.html 获取它。它几乎完全包含了 @zett42 在上面评论中展示的内容。 - dotNET
我的问题是 index.html 文件在项目的根目录下。一旦我将它移动到 public 目录中,Vue CLI 就会捕捉到我对 <title> 的更改。 - Fearnbuster

2

您可以通过修改vue.config.js文件来使用自定义的index.html页面:


module.exports = {
  publicPath: '/',
  chainWebpack: config => {
    config
      .plugin("html")
      .tap(args => {
        args[0].template = './public/index.html'
        return args
      })
  }
};


1
这应该是被接受的答案,因为根据项目(设置)更改标题比在实际文件中硬编码更有意义。 - Lucas Venturini

0
您可以通过以下命令,在 package.json 文件的 scripts 部分中添加 postinstall"postinstall": "cp ./public/index.html ./node_modules/@vue/cli-service/lib/config/index-default.html"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接