简体   繁体   中英

Why is component props undefined (vue router)

I am new to Vue and I'm trying to learn how to apply Vue router. I got normal routing to work no problem. When I try to use dynamic routing everything continued to work fine. When I tried to pass props to dynamic routes however my code breaks.

I'm using these cdn versions of Vue and Vue router which are the versions suggested by the official websites: - https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js - https://unpkg.com/vue-router@2.0.0/dist/vue-router.js

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

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

When I navigate to the 'Name' page the static text renders fine but the dynamic text fails to load. I added a button that will log the value of name from props and from $route.params to the user. When clicked it turns out that the value of name in props is undefined but the value of name from params is correct. Why is this?

If you're sticking with VueRouter@2.0.0 or lower :
The name that you expect is not passed as a prop but as a route param, cf. Dynamic route matching .

You need to access it from your template as follow : $route.params.name .

You could also use a computed value instead.

If you can update VueRouter
As stated in another answer, and according to the release note of VueRouter@2.2.0 , passing down route params as props has only been introduced in v2.2.0, you were using v2.0.0. If you would like to use props you would need to update to (at least) v2.2.0.

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