【问题标题】:Vuejs props use in the client component客户端组件中使用的 Vuejs 道具
【发布时间】:2019-06-07 13:43:16
【问题描述】:

您好,我正在尝试将一个值作为道具传递给子组件,并尝试在子组件的 created 钩子中使用该值,但它没有被设置。请参阅下面的示例,

<!-- 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'。我错过了什么?任何帮助表示赞赏。

【问题讨论】:

  • 这一行的undefined 也必须是var id = this.$route.params.id;。如果id 确实存在,请先尝试控制台记录它。
  • 它不是未定义的,因为父组件是从路由器调用中呈现的。我遵循路由代码,{ path: '/customers/:id', component: Customer }
  • 您不需要模板中的this.customer_id 中的this。也请发布您的路由器对象。
  • 我得到 linter 错误,而在子组件中没有使用 'this'。错误字符串是“模块警告(来自./node_modules/eslint-loader/index.js):错误:'customer_id'未定义(no-undef)”
  • 您能否创建一个小提琴或代码框,我们可以在其中看到发生的问题。我在本地尝试过,无法重现。

标签: vue.js vue-component


【解决方案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>

【讨论】:

  • 通过路由传递的参数总是被赋值。
猜你喜欢
  • 1970-01-01
  • 2019-11-14
  • 1970-01-01
  • 1970-01-01
  • 2021-09-28
  • 1970-01-01
  • 2019-01-27
  • 2018-02-25
  • 1970-01-01
相关资源
最近更新 更多