简体   繁体   English

路由器模板中的 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';
    }
  }
})

When I click the "Level 1" link, the result I expect to see is:当我点击“Level 1”链接时,我期望看到的结果是:

|1|HELLO| |1|你好|

The result I actually see is:我实际看到的结果是:

|1|| |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:有2个问题:

1) There's an error: 1)有一个错误:

Cannot use <template> as component root element because it may contain multiple nodes.不能使用<template>作为组件根元素,因为它可能包含多个节点。

So change that to a div .因此,将其更改为div When using the Vue CLI, templates are wrapped in <template> but there still needs to be a different root element inside of it.使用 Vue CLI 时,模板被包裹在<template>中,但其中仍然需要有不同的根元素。

2) The Level component has a prop called message but it isn't passed. 2) Level组件有一个名为message的道具,但没有通过。 The Home route passes id but not message . Home路由通过id但不通过message Home can't pass message at the moment, because it's in the root component, and Home didn't receive it. Home目前无法传递message ,因为它在根组件中,而Home没有收到它。

You could:你可以:

  • Use Vuex to solve this most cleanly用Vuex最干净的解决这个问题
  • Define message in Home instead of the root and pass it to LevelHome而不是 root 中定义message并将其传递给Level
  • Pass the message from root to Home and then again from Home to Levelmessage从 root 传递到Home ,然后再从Home传递到Level

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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