Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

在SSR环境下无法渲染title,建议修改server.js,文中给出了如何修复这个bug #7

Closed
berwin opened this issue Jul 30, 2018 · 3 comments

Comments

@berwin
Copy link
Contributor

berwin commented Jul 30, 2018

无法在SSR环境下成功渲染出title信息。也就是说在查看源码里是看不到title的。

因为一个路由下有可能有很多个组件,然后一个路由被匹配时通常只有一个组件设置了meta信息。

所以代码中的逻辑会导致后面没有设置meta信息的组件将前面设置了meta信息的组件覆盖掉。导致meta信息失效。

经过排查发现问题是因为项目最后一次commit导致的 7a98388

当时是在参数中给了一个默认值,这会导致在SSR环境下无法渲染Title的问题。

代码中是这样写的

export default function (context, metaInfo = {title: ''}) {
  if (context && metaInfo) {
    context.title = metaInfo.title
    context.render = {}
    Object.keys(metaInfo).forEach(info => {
      if (info === 'title') return
      context.render[info] = function () {
        let metaNd = ''
        if (metaInfo[info]) {
          metaInfo[info].forEach((item) => {
            let str = `<${info} data-vue-meta-info="true"`
            Object.keys(item).forEach(key => {
              str += `${key}="${item[key]}"`
            })
            str += `></${info}>\n`
            metaNd += str
          })
        }
        return metaNd
      }.bind(this)
    })
  }
}

这就导致下面这行代码实际上是无效的判断。

if (context && metaInfo) {

因为无论怎样都是为true

所以导致SSR环境下无法成功设置title。因为context.title = metaInfo.title这行代码会将已经设置了Title的context.title被没有设置Title的metaInfo.title覆盖掉。

建议将代码改成下面这样:

export default function (context) {
  if (context && metaInfo) {
    context.title = metaInfo.title || ''
@muwoo
Copy link
Owner

muwoo commented Jul 31, 2018

@berwin 感谢,你可以直接提一个PR

@berwin
Copy link
Contributor Author

berwin commented Jul 31, 2018

@muwoo 哈哈哈,已经提了一个PR,合并完代码后需要你在npm上发布一个新版本。

另外,我在修改这个代码的时候,发现可能是我的rollup版本比你的版本号高,rollup强制让我在配置文件中新增一个output字段,然后我把这个字段加上去了。

然后我按照你之前的开发习惯手动修改了package.json的版本号~

正常应该是使用 npm version patch 升级补丁版本号哒~ 😄😄

muwoo added a commit that referenced this issue Jul 31, 2018
@muwoo
Copy link
Owner

muwoo commented Jul 31, 2018

恩 感谢~

@muwoo muwoo closed this as completed Jul 31, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants