Vuejs道具在客户端组件中的使用

时间:2019-01-13 07:05:08

标签: vue.js vue-component

嗨,我正在尝试将值作为道具传递给子组件,并尝试在子组件的已创建钩子中使用此值,但未设置它。参见下面的示例,

<!-- Parent component -->
<template>
  <div>
     <details
       :customer_id = this.customer_id
       :foo = "bar" />
  </div>
</template>
<script>
  import CustomerDetail from './CustomerDetails';
  export default {
    name: 'Customer',
    data: function() {
      return {
        customer_id: '',
     }
  components: {
    'detail': CustomerDetail   
  },

  created: function() {
    var id = this.$route.params.id;
    this.customer_id = id;
  } // created
}  
</script>

<!-- Details component -->
<template>
  <div>
    <h1>{{foo}}</h1>
  </div>
</template>
<script>
  export default {
    name: 'CustomerDetail',
    props: ['customer_id', 'foo']     

    created: function() {
      console.log(this.customer_id); <!-- -->
    } // created
  }
</script>

如上面的代码所示,当呈现子组件时,可能会导致未定义子组件的created()挂钩中的customer_id乘以时间。如果在同一视图上发生热加载,则偶尔会显示该消息。我如何确保此值始终可用。在这种情况下,我想进行服务器呼叫以获取客户详细信息。同时{{foo}}正确显示值'bar'。我想念什么?任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

已注册的子组件实际上可以直接访问路由参数,因为您使用的是Dynamic Route Matching,因此您可以简单地通过$routes.params.*从子组件本身获取动态参数。

const Customer = {
  template: `
    <div>
      <h3>Customer ID: {{$route.params.id}}</h3>
    </div>
  `
}

const routes = [
  { path: '/customers/:id', component: Customer }
];

new Vue({
  el: '#app',

  router: new VueRouter({
    routes
  }),

  data() {
    return {
      bar: 'Doh!',
      //customer_id: '',
    }
  },
  
  components: {
    CustomerDetails: {
      template: `
        <div>
          <h1>Value from parent: <em>{{foo}}</em></h1>
        </div>
      `,

      props: ['foo']
    }
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-router/3.0.2/vue-router.min.js"></script>

<div id="app">
  <div>
    <label>View profile:</label>
    <router-link to="/customers/john">John</router-link>
    <router-link to="/customers/doe">Doe</router-link>
    
    <router-view></router-view>
  <div>
  
    <customer-details :foo="bar"></customer-details>
</div>