VueRouter does not receive meta property in router-link tag

Viewed 440

I'm trying to pass meta fields via <router-link> tag. Like this:

<router-link :to="{path: '/inlineMeta', meta: {title: 'Inline meta'}}">
    Inline meta
</router-link>

I want to achieve this because I can dynamically pass metas from a backend framework directly on the tag itself. Declaring routes option in a JS file simply does not have that power.

Theoretically, any object passed via to prop should be pushed to router stack right? But in this case it doesn't seem like so.

If I declare meta in routes option, it definitely works. There is no doubt about that.

I wonder if it's possible to do so, and how would I do that?


A small fiddle to illustrate the problem. Click on URLs and notice the console. I can't get StackOverflow snippet to work properly.

JSFiddle

Vue.use(VueRouter);

const cComponent = {
  data() {
    return {
      fetchedData: null
    }
  },
  template: `<div>The meta is: {{$route.meta.title}}</div>`,
}
const routes = [{
    path: "/inlineMeta",
    component: cComponent,
  },
  {
    path: "/routeMeta",
    meta: {
      title: 'Meta declared in routes'
    },
    component: cComponent,
  }
]

const router = new VueRouter({
  mode: "history",
  routes,
})

router.beforeEach((to, from, next) => {
  console.log("The meta title is : " + to.meta.title);
})

const app = new Vue({
  el: "#app",
  router,
})
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<script src="   https://unpkg.com/vue-router@3.5.1/dist/vue-router.js"></script>

<div id="app">
  <router-link :to="{path: '/inlineMeta', meta: {title: 'Inline meta'}}">Inline meta</router-link>
  <router-link :to="{path: '/routeMeta'}">Meta declared in routes</router-link>
  <router-view></router-view>
</div>

1 Answers

If you want to pass the parameters between two components, use props. v-bind:to in <route-link> is just used for route match, so you can't use it to set the value of meta. If you want to set the meta without declaring it in route, i think using "this.$route.meta.title="Inline meta" " in js. like using the click event:

<li @click="setMeta">
  <router-link :to="{path: '/inlineMeta'}">
    Inline meta
  </router-link>
</li>

and in js:

method:{
    setMeta(){
      this.$route.meta.title="Inline meta";
    }
}

you can also use mounted() in the new component you just routed to like :

mounted(){
  this.$route.meta.title="Inline meta"
}

and meta will be modified after reloading This may work though it may looks not that elegant.

Related