Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get props in child component using v-bind object

Tags:

vue.js

vuejs2

I want to pass all the properties in an object as props, and use v-bind without an argument.

But how can I get the props in the child without having to declare the props in the child component?

For example, in the code below item is an object.

Parent component:

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

Child component:

<script>
  export default {
    name: 'cusDom',
    props: [],   // HOW TO GET THE props, because I have it empty/no arguments HERE?
    data() {
      return {};
    },
    mounted() {
    }
  }
</script>
like image 601
Liu xiao Avatar asked Mar 18 '18 06:03

Liu xiao


People also ask

How do you get props in child component Vue?

The way it works is that you define your data on the parent component and give it a value, then you go to the child component that needs that data and pass the value to a prop attribute so the data becomes a property in the child component. You can use the root component (App.

Can you use V model on props?

In 2.2 we introduced the model component option that allows the component to customize the prop and event to use for v-model .


1 Answers

Even when using v-bind, you still have to declare them as props.

If you don't they will be $attrs.

See demo below, should make it clear.

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/[email protected]/dist/vue.min.js"></script>

<div id="app">
  <p>{{ message }}</p>
  <child v-bind="stuff"></child>
</div>
like image 146
acdcjunior Avatar answered Oct 29 '22 10:10

acdcjunior