vuejs/vue-hackernews-2.0

about the issue of Title injection, client rendering is invalid

toffeeBlock opened this issue · 0 comments

// title.js
const serverTitleMixin = {
  created () {
    const title = getTitle(this)
    if (title) {
      this.$ssrContext.title = `Vue HN 2.0 | ${title}`
    }
  }
}

const clientTitleMixin = {
  mounted () {
    const title = getTitle(this)
    if (title) {
      document.title = `Vue HN 2.0 | ${title}`
    }
  }
}
export default process.env.VUE_ENV === 'server'
  ? serverTitleMixin
  : clientTitleMixin
// app.js
Vue.mixin(titleMixin)

The injection of title is set according to demo,but I have some problems:
I have two pages, a detail page and a home page, detail.vue The title option is set in, index.vue The title option is not set. When I use router link to jump from the details page to the first page, the title is still the title of the details page, instead of the default title.
although server.js the default title attribute is set for the context object in, like this:

const context = {
    title: 'default title',
    url: req.url
 }

but the client rendering does not go server.js, so my home page title is always the title of the details page.

I don't want to set the title option on every Vue page

That's what I do:
In client- entry.js globalinjection beforeRouteEnter, internal setting title. Title.js only title global injection is performed to the server, like this:

// client-entry.js
beforeRouteEnter(to, from, next) {
    // 在回调中访问实例!!!
    next(vm => {
      const { title } = vm.$options
      document.title = title
        ? (typeof title === 'function'? title.call(vm): title)
        : 'default title'
    })
  }
// title.js
function getTitle(vm) {
  const { title } = vm.$options
  if (title) {
    return typeof title === 'function'
      ? title.call(vm)
      : title
  }
}

const serverTitleMixin = {
  created() {
    const title = getTitle(this)
    if (title) {
      this.$ssrContext.title = title
    }
  }
}
export default serverTitleMixin
// app.js
import titleMixin from './utils/title'
if(process.env.VUE_ENV === 'server') Vue.mixin(titleMixin)

I don't think that's a problem. Please have a look is there any problem with this setting?