vue.js - VueRouter 没有收到路由器链接标签中的元属性
问题描述
我正在尝试通过标签传递meta
字段。<router-link>
像这样:
<router-link :to="{path: '/inlineMeta', meta: {title: 'Inline meta'}}">
Inline meta
</router-link>
我想实现这一点,因为我可以直接在标签本身上动态地从后端框架传递元数据。在 JS 文件中声明routes
选项根本没有这种权力。
从理论上讲,通过 prop 传递的任何对象都应该被推入router
堆栈,对吗?但在这种情况下,情况似乎并非如此。
如果我meta
在routes
选项中声明,它肯定有效。毫无疑问。
我想知道是否有可能这样做,我该怎么做?
一个小小提琴来说明问题。单击 URL 并注意控制台。我无法让 StackOverflow 片段正常工作。
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>
解决方案
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.
推荐阅读
- eclipse - Eclipse:如何更改当前单词背景颜色?
- java - Retrofit/OkHttp 移除 Transfer-Encoding 标头
- android - 无法使用 Android Management API 重新启动设备
- node.js - 有没有使用 Puppeteer 消除所有模式和 cookie 警告的通用方法?
- azure-devops - 在 azure devops 中签署 android 应用程序包时出错
- python - Python Tkinter 按钮数量根据选定的 RadioButton 更改
- c# - 如何使用 LINQ 从数据库中返回两个特定列?
- wpf - 依赖属性未在初始绑定时传递默认值
- sql - 在 SQL 中使用 Group By 和 Aggregate - 获取错误“选择列表中的列无效,因为它不包含在聚合函数或 GROUP BY 中”
- javascript - 我有 jquery 上下滑动的问题