【问题标题】:Why is component props undefined (vue router)为什么组件道具未定义(vue路由器)
【发布时间】:2018-11-04 05:43:52
【问题描述】:

我是 Vue 的新手,我正在尝试学习如何应用 Vue 路由器。我有正常的路由工作没问题。当我尝试使用动态路由时,一切都继续正常工作。当我尝试将道具传递给动态路由时,我的代码中断了。

我正在使用这些cdn版本的Vue和Vue路由器,这是官方网站建议的版本: - https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js - https://unpkg.com/vue-router@2.0.0/dist/vue-router.js

HTML

<div id="app">
  <h1>{{ message }}</h1>
  <nav>
    <router-link to="/">Home</router-link>
    <router-link to="/about">About</router-link>
    <router-link to="/user/John">Name</router-link>
  </nav>
  <!-- route outlet -->
  <!-- component matched by route will render here -->
  <router-view></router-view>
</div>

JS

// Route components
  const Home = { template: '<div>Home</div>' };
  const About = { template: '<div>About</div>' };
  const User = { props: ['name'], template: `
    <div>
      <div>User {{ name }}</div>
      <button @click="checkName">Check</button>
    </div>`,
    methods: {
      checkName: function() {
        console.log('Params name: ' + this.$route.params.name);
        console.log('Props name: ' + this.name);
      }
    }
  };

  // Routes for router
  const routes = [
    { path: '/', component: Home },
    { path: '/home', redirect: Home },
    { path: '/about', component: About },
    { path: '/user/:name', component: User, props: true }
  ];

  const router = new VueRouter({
    routes: routes
  });

  const app = new Vue({
    el: '#app',
    data: {
      message: 'VueJS Router'
    },
    router: router
  });

当我导航到“名称”页面时,静态文本呈现正常,但动态文本无法加载。我添加了一个按钮,它将从 props 和 $route.params 向用户记录 name 的值。点击后发现 props 中 name 的值是未定义的,但 params 中 name 的值是正确的。为什么是这样?

【问题讨论】:

  • name 是 url 参数而不是道具

标签: javascript vue.js vuejs2 vue-component vue-router


【解决方案1】:

如果您坚持使用 VueRouter@2.0.0 或更低版本:
您期望的 name 不是作为道具传递,而是作为路由参数传递,cf. Dynamic route matching

您需要从您的模板中访问它,如下所示:$route.params.name

您也可以使用计算值。

如果可以更新 VueRouter
如另一个答案所述,并且根据release note of VueRouter@2.2.0,仅在 v2.2.0 中引入了将路由参数作为道具传递,您使用的是 v2.0.0。如果您想使用道具,您需要更新到(至少)v2.2.0。

【讨论】:

  • 我真的只是从这里复制代码。我不确定为什么我没有得到想要的结果。我如何将值作为道具传递? router.vuejs.org/guide/essentials/…
  • 由于您将其用作router-view,因此一旦可用,您就不能将其作为道具传递。如果您可以从其他地方访问它,我仍然不确定为什么您绝对需要它作为道具
  • 我不需要它作为道具,只是文档说我可以使用道具,但我不知道为什么它不起作用。同样在这里medium.com/frontend-fun/…我最初逐字复制了它,但它仍然不起作用。我一定是错过了什么
  • 这很有趣,理论上你所拥有的应该按预期工作。您在创建路由器之前尝试过使用Vue.use(VueRouter) 吗?
  • 我没有尝试使用Vue.use(VueRouter)。我认为将路由器传递给我的 Vue 实例(如文档中所述)就足够了
【解决方案2】:

【讨论】:

    猜你喜欢
    • 2021-09-11
    • 2021-06-06
    • 2021-08-21
    • 2020-08-03
    • 2019-02-05
    • 1970-01-01
    • 1970-01-01
    • 2021-11-28
    • 2021-01-12
    相关资源
    最近更新 更多