[Vuejs]-Can I pass props to a child component and use the data in the parent component in Vue

1👍

You can’t use the same word/property name (sections in your case) for data and props.

0👍

I assume your code is the parent component:

// parent.vue
<template>
  <div class="hello">
    <div v-for="(section, index) in sections" :key="index">
      <p>{{section.name}}</p>
      <p>{{section.type}}</p>
    </div>
    <my-child-component :sections="sections" />
  </div>
</template>

<script>
import MyChildComponent from '~/components/MyChildComponent.vue'

export default {
  name: "HelloWorld",
  components: {
    MyChildComponent
  },
  data() {
    return {
      sections: [
        {
          name: "scoop",
          type: "boulder"
        },
        {
          name: "pew pew",
          type: "roped"
        }
      ]
    }
  },
  methods: {
    consoleSections() {
      console.log(this.sections) // the way to use data in function
    }
  }
}
</script>
// MyChildComponent.vue
<template>
  <div class="hello">
    <div v-for="(section, index) in sections" :key="index">
      <p>{{section.name}}</p>
      <p>{{section.type}}</p>
    </div>
  </div>
</template>

<script>

export default {
  name: "ChildHelloWorld",
  props: ['sections'],
  methods: {
    consoleSections() {
      console.log(this.sections) // the way to use data in child
    }
  }
}
</script>

Take a look in the vue guide about component: https://v2.vuejs.org/v2/guide/components.html

Leave a comment