简体   繁体   中英

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';
    }
  }
})

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.

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 in Home instead of the root and pass it to Level
  • Pass the message from root to Home and then again from Home to Level

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM