vuejs / vue-hackernews-2.0

HackerNews clone built with Vue 2.0, vue-router & vuex, with server-side rendering
MIT License
10.96k stars 2.15k forks source link

How to get to $route in head: {}? #370

Open SkipTyler opened 5 years ago

SkipTyler commented 5 years ago

Hello. For seo, I need to generate meta tags. For this, I have a mixin that is used globally.

const serverHeadMixin = {
  created() {
    const { head } = this.$options;

    if (head) {
      const {title} = head;
      if (title)
        this.$ssrContext.title = getString(this, title);

      const {meta} = head;
      if (meta)
        this.$ssrContext.meta = `\n${getMeta(this, meta, true)}`
    }
  }
};

It takes data from head

The head itself is located in the component.

head: {
    title: 'title',
    meta: []
},

And here I need to turn to $route.params

I managed to reach out to i18n, which is in the project this way.

<script>
     import {createI18n} from 'Util / i18n';
     const i18n = createI18n ();
     export default {
...

and use it in head title: i18n.t ('meta.mainPage.title')

i18n.js itself

export function createI18n () {
   return new VueI18n ({
     locale: 'ua',
     fallbackLocale: 'ua',
     messages: {...}
   })
}

But with a router in any way. I need to get the parameters of the current route. How can I do that?

file router/index.js

export function createRouter (i18n) {
    const router = new Router ({
        mode: 'history',
        fallback: false,
        routes: [...]
    });
    return router;
}

I managed to reach the router like this

import {createApp} from '../app';
const {router} = createApp ();

But currentRoute mutable object

app.js file

import Vue from 'vue'
import App from './App'
import {createStore} from './store'
import {createRouter} from './router'
import {createI18n} from "Util / i18n";
import {sync} from 'vuex-router-sync'
import headMixin from './util/title'

Vue.mixin (headMixin);

export function createApp () {
  const store = createStore ();
  const i18n = createI18n ();
  const router = createRouter (i18n);

  sync (store, router);
  
  const app = new Vue ({
    router
    store,
    i18n,
    render: h => h (App)
  });

  return {app, router, store}
}