App下載

Vue 中子組件訪問父組件數據

猿友 2021-02-22 18:06:59 瀏覽數 (6239)
反饋

props

官方解釋:所有的 prop 都使得其父子 prop 之間形成了一個單向下行綁定:父級 prop 的更新會向下流動到子組件中,但是反過來則不行。這樣會防止從子組件意外變更父級組件的狀態(tài),從而導致你的應用的數據流向難以理解。

我們可以這樣理解,當父級組件的數據發(fā)生改變的時候,子級組件接受的數據也會自動發(fā)生改變,但子級組件改變的數據不能對父級數據進行影響這也就是單向下行綁定。

但子組件不能直接引用父組件中的數據。我們需要進行引用。

子組件對父組件的數據引用

我們以兩個 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 人點贊