Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

The child component in Vue accesses the parent component data


May 30, 2021 Article blog



props

Official explanation: All props make a one-down binding between their parent and child props: updates to the parent prop flow down to the child component, but vice versa. This prevents accidental changes in the state of the parent component from the child component, making your app's data flow difficult to understand.

We can understand that when the data of the parent component changes, the data accepted by the child component changes automatically, but the data that the child component changes does not affect the parent data, which is a single downstream binding.

However, child components cannot directly reference data in the parent component. We need to make a reference.

The child component's data reference to the parent component

Let's take two vue interfaces as an example

The parent component is HomeComponent and the child component is TopArticles.

HomeComponent.vue

<script>
export default {
  name: "HomeComponents",
  components: {TopCoders, TopArticles, ComingCompetitions, TopNews},
  data() {
    return {
      topArticle:[
        {
          title:'title1',
          url:'url1',
          author:'author1'
        },
          {
          title:'title2',
          url:'url2',
          author:'author2'
        }
      ],
    }
  }
}
</script>

HomeComponent needs to pass binding data to child components when referenced. i.e.: top-articles "topArticle"

HomeComponent.vue

<template>
  <div style="width: 100%;min-width: 1200px;">
        <top-articles class="articles" :top-articles="topArticle"></top-articles>
  </div>
</template>

TopArticle in data is the data of the parent component that needs to be referenced in the topArticle interface.

Specify the type of data

topArticles.vue

<script>
export default {
  name: "topArticle",
  props: {
    topArticles: {
      // 指定类型
      Type: Array,
      required: true
    },
  },
}
</script>

Data presentation

topArticles.vue

<template>
  <div>
    <sui-list>
      <sui-list-item v-for="(item, key) in topArticles">
        <span style="font-size: 18px">{{item.title}}</span>
        <span style="font-size: 18px">{{item.author}}</span>
      </sui-list-item>
    </sui-list>
  </div>
</template>

Effect display

 The child component in Vue accesses the parent component data1


Recommended courses: Vue 2.0 micro-class, vue.js1.0 tutorial