Vue 中子组件访问父组件数据

猿友 2021-02-22 18:06:59 浏览数 (5376)
反馈

props

官方解释:所有的 prop 都使得其父子 prop 之间形成了一个单向下行绑定:父级 prop 的更新会向下流动到子组件中,但是反过来则不行。这样会防止从子组件意外变更父级组件的状态,从而导致你的应用的数据流向难以理解。

我们可以这样理解,当父级组件的数据发生改变的时候,子级组件接受的数据也会自动发生改变,但子级组件改变的数据不能对父级数据进行影响这也就是单向下行绑定。

但子组件不能直接引用父组件中的数据。我们需要进行引用。

子组件对父组件的数据引用

我们以两个 vue 界面为例

父组件为 HomeComponent,子组件为 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 在引用子组件的时候需要向子组件传递绑定数据。即 :top-articles=“topArticle”

HomeComponent.vue

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

data 中的 topArticle 为 topArticle 界面中需要引用的父级组件的数据。

指定数据的类型

topArticles.vue

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

数据展示

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>

效果展示

在这里插入图片描述


推荐课程:Vue2.0微课vue.js1.0教程


0 人点赞