问题
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';
}
}
})
When I click the "Level 1" link, the result I expect to see is:
|1|HELLO|
The result I actually see is:
|1||
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.
回答1:
There are 2 issues:
1) There's an error:
Cannot use
<template>
as component root element because it may contain multiple nodes.
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) 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.
You could:
- 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
来源:https://stackoverflow.com/questions/61314809/vue-computed-property-in-router-template