首页 > 解决方案 > VueRouter 没有收到路由器链接标签中的元属性

问题描述

我正在尝试通过标签传递meta字段。<router-link>像这样:

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

我想实现这一点,因为我可以直接在标签本身上动态地从后端框架传递元数据。在 JS 文件中声明routes选项根本没有这种权力。

从理论上讲,通过 prop 传递的任何对象应该被推入router堆栈,对吗?但在这种情况下,情况似乎并非如此。

如果我metaroutes选项中声明,它肯定有效。毫无疑问。

我想知道是否有可能这样做,我该怎么做?


一个小小提琴来说明问题。单击 URL 并注意控制台。我无法让 StackOverflow 片段正常工作。

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>

标签: vue.jsvuejs2vue-componentvue-router

解决方案


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.


推荐阅读