路由模板中的Vue计算属性 [英] Vue computed property in router template
问题描述
我无法理解如何通过路由器将计算属性一直传到我的模板.这是我正在做的事情的基本想法:
I'm having trouble understanding how to get a computed property all the way out through the router to my template. Here's a basic idea of what I'm doing:
const Home = {
template: '<router-link to="/level/1">Level 1</router-link>'
}
const Level = {
template: '<template>|{{ id }}|{{ message }}|</template>',
props: ['id','message']
}
const router = new VueRouter({
routes: [
{ path: '/', component: Home, props: true },
{ path: '/level/:id', component: Level, props: true }
]
})
const vm = new Vue({
el: '#app',
router,
template: '<router-view></router-view>',
computed: {
message() {
return 'HELLO';
}
}
})
当我点击Level 1"链接时,我希望看到的结果是:
When I click the "Level 1" link, the result I expect to see is:
|1|你好|
我实际看到的结果是:
|1||
最终的用法将比这更实用,但希望这足以暴露我对 props、路由或计算属性不了解的任何内容.
The final usage will be a bit more functional than this, but hopefully that's enough to expose whatever it is that I'm not understanding about props, or routing, or computed properties.
推荐答案
有2个问题:
1) 出现错误:
不能使用 作为组件根元素,因为它可能包含多个节点.
Cannot use
<template>
as component root element because it may contain multiple nodes.
因此将其更改为 div
.使用 Vue CLI 时,模板包含在 中,但其中仍需要有不同的根元素.
So change that to a div
. When using the Vue CLI, templates are wrapped in <template>
but there still needs to be a different root element inside of it.
2) Level
组件有一个名为 message
的道具,但它没有被传递.Home
路由通过 id
但不通过 message
.Home
暂时无法传递message
,因为它在根组件中,而Home
没有收到.
2) The Level
component has a prop called message
but it isn't passed. The Home
route passes id
but not message
. Home
can't pass message
at the moment, because it's in the root component, and Home
didn't receive it.
你可以:
- 使用 Vuex 最干净地解决这个问题
- 在
Home
中定义message
而不是root 并将其传递给Level
- 将
message
从 root 传递到Home
,然后再从Home
传递到Level
- Use Vuex to solve this most cleanly
- Define
message
inHome
instead of the root and pass it toLevel
- Pass the
message
from root toHome
and then again fromHome
toLevel
这篇关于路由模板中的Vue计算属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!