App下載

Vue 中子組件訪問父組件數(shù)據(jù)

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

props

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

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

但子組件不能直接引用父組件中的數(shù)據(jù)。我們需要進(jìn)行引用。

子組件對(duì)父組件的數(shù)據(jù)引用

我們以兩個(gè) 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 在引用子組件的時(shí)候需要向子組件傳遞綁定數(shù)據(jù)。即 :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 界面中需要引用的父級(jí)組件的數(shù)據(jù)。

指定數(shù)據(jù)的類型

topArticles.vue

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

數(shù)據(jù)展示

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 人點(diǎn)贊