【问题标题】:How to get props in child component using v-bind object如何使用 v-bind 对象获取子组件中的道具
【发布时间】:2018-08-26 23:00:08
【问题描述】:

我想将对象中的所有属性作为props 传递,并使用不带参数的v-bind

但是如何在子组件中获取props 而无需在子组件中声明道具?

例如,在下面的代码中 item 是一个对象。

父组件:

<div v-for="item in domArr" :key="item.id">
  <cus-dom v-bind="item"></cus-dom>
</div>

子组件:

<script>
  export default {
    name: 'cusDom',
    props: [],   // HOW TO GET THE props, because I have it empty/no arguments HERE?
    data() {
      return {};
    },
    mounted() {
    }
  }
</script>

【问题讨论】:

  • 对不起。我会尽快编辑。

标签: vue.js vuejs2


【解决方案1】:

即使使用v-bind,您仍然需要将它们声明为props

如果您不这样做,他们将是 $attrs

请看下面的演示,应该清楚。

Vue.component('child', {
  props: ['a'],
  template: `<button @click="go">PROPS AND ATTRS</button>`,
  mounted() {
    this.go()
  },
  methods: {
    go() {
      console.log(
      '$attrs:', JSON.stringify(this.$attrs), '- $props:', JSON.stringify(this.$props),
      '- a:', this.a, '- b:', this.b)
    }
  }
});
new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!',
    stuff: {a: 1, b: 2}
  }
})
<script src="https://unpkg.com/vue@2.5.16/dist/vue.min.js"></script>

<div id="app">
  <p>{{ message }}</p>
  <child v-bind="stuff"></child>
</div>

【讨论】:

  • 当然,例如,您可以使用this.$attrs.b 访问属性。
  • 哦,是的,我明白了。感谢您的帮助。
猜你喜欢
  • 2019-11-12
  • 1970-01-01
  • 2020-06-09
  • 2023-02-06
  • 2021-01-02
  • 2019-02-08
  • 2019-09-05
  • 1970-01-01
  • 2021-07-16
相关资源
最近更新 更多