繁体   English   中英

路由器模板中的 Vue 计算属性

[英]Vue computed property in router template

我无法理解如何通过路由器一直到我的模板获取计算属性。 这是我在做什么的基本想法:

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”链接时,我期望看到的结果是:

|1|你好|

我实际看到的结果是:

|1||

最终的用法会比这更实用一些,但希望这足以暴露我对道具、路由或计算属性不了解的任何内容。

有2个问题:

1)有一个错误:

不能使用<template>作为组件根元素,因为它可能包含多个节点。

因此,将其更改为div 使用 Vue CLI 时,模板被包裹在<template>中,但其中仍然需要有不同的根元素。

2) Level组件有一个名为message的道具,但没有通过。 Home路由通过id但不通过message Home目前无法传递message ,因为它在根组件中,而Home没有收到它。

你可以:

  • 用Vuex最干净的解决这个问题
  • Home而不是 root 中定义message并将其传递给Level
  • message从 root 传递到Home ,然后再从Home传递到Level

暂无
暂无

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

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