我希望能够根据路径将元道具列表传递给多个组件。为了实现这个目标,我做了以下工作。todo列表是硬编码的,这就是我想要的。它不是动态加载的。我的解决方案只有在我从列表中点击进入项目时才有效。然而,如果我尝试导航直接刷新页面。我失去了 meta
参数。
问题是在页面刷新时如何维护?有没有更好的管理方法?
codesandbox.iosvue-router-3oblk https:/codesandbox.iosvue-router-3oblk。
// todo.vue
<template>
<div class="todos">
<h1>Todos</h1>
<stats :value="total" label="Total"></stats>
<stats :value="completed" label="Completed"></stats>
<stats :value="pending" label="Pending"></stats>
<todo-list :todos="todos"></todo-list>
</div>
</template>
<script>
import Stats from "../components/Stats";
import TodoList from "../components/TodoList";
export default {
name: "Home",
components: {
"todo-list": TodoList,
stats: Stats
},
data() {
return {
limit: 20,
todos: [
{
userId: 1,
id: 1,
title: "delectus aut autem",
completed: false
},
{
userId: 1,
id: 2,
title: "quis ut nam facilis et officia qui",
completed: false
}
]
};
},
computed: {
total: function() {
return this.todos.length;
},
completed: function() {
return this.todos.filter(function(todo) {
return todo.completed === true;
}).length;
},
pending: function() {
return this.todos.filter(function(todo) {
return todo.completed === false;
}).length;
}
}
};
</script>
// todo list
<template>
<ul v-if="todos.length > 0">
<li v-for="todo in todos" :key="todo.id">
<router-link :to="{name: 'singletodo', params: {id: todo.id, meta: todo}}">
<span :class="todo.completed ? 'completed' : ''">{{ todo.title }}</span>
</router-link>
</li>
</ul>
</template>
<script>
export default {
name: "TodoList",
props: ["todos"]
};
</script>
<style scoped>
.completed {
color: gray;
text-decoration: line-through;
}
ul {
margin-top: 2em;
margin-left: 1em;
}
li {
list-style: square;
}
</style>
// Router config
const routes = [
{ path: "/", name: "home", component: Home },
{ path: "/about", name: "about", component: About },
{ path: "/todos", name: "todo", component: Todos },
{ path: "/todos/:id", name: "singletodo", component: TodoSingle }
];
const router = new Router({
routes
});
更新你的路由,像这样
// Router config
const routes = [
{ path: "/", name: "home", component: Home },
{ path: "/about", name: "about", component: About },
{ path: "/todos", name: "todo", component: Todos },
{ path: "/todos/:id/:meta?", name: "singletodo", component: TodoSingle }
];
这将元参数作为可选参数添加到URL中。 去掉?,使其成为必需的。 你需要这个来允许页面刷新。