Vue computed property in router template

元气小坏坏 提交于 2021-01-29 13:52:44

问题


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 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


来源:https://stackoverflow.com/questions/61314809/vue-computed-property-in-router-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!