1.組件間數據傳遞以及父子組件的引用----Vue實踐

父子組件的引用

直接上代碼吧 下面是一個組件List.vue的內容:

<template>
	<div class="col-md-8">
        <h3 class="reply">評論回覆:</h3>
        <h2 style='display: none'>暫無評論,點擊左側添加評論!!!</h2>
        <ul class="list-group">
        	<!--下面可以看到  我們遍歷了comments屬性 並且將每個comment 通過 Item的屬性comment 使用:comment 傳遞了數據 -->
          <Item v-for="(comment,index) in comments" :key="index" :comment='comment'></Item>
        </ul>
      </div>
</template>

<script>
	import Item from './Item.vue'
	
	export default {
		// 用於其他組件使用本組件時,通過:屬性名稱來傳遞數據  ,也就是說其他 地方使用該組件時 使用了':comments' 來傳遞屬性
		props:['comments'],
		// components 是指本組件使用了那些另外的組件,注意:組件不用引號包括 因爲 已經通過 import 命名過了
		components:{Item}
	}
</script>

<style>
	.reply {
  margin-top: 0px;
}

</style>

總結:
父組件List.vue使用子組件Item.vue :

1.在script中 import(引入)

2.在export default中的components中聲明

組件間數據傳遞

下面是Item.vue 的內容:

<template>
	<li class="list-group-item">
		<div class="handle">
			<a href="javascript:;">刪除</a>
		</div>
		<p class="user"><span>{{comment.name}}</span><span>說:</span></p>
		<p class="centence">{{comment.content}}</p>
	</li>
</template>

<script>
	export default {
		props:['comment']
	}
</script>

<style>
li {
  transition: .5s;
  overflow: hidden;
}

.handle {
  width: 40px;
  border: 1px solid #ccc;
  background: #fff;
  position: absolute;
  right: 10px;
  top: 1px;
  text-align: center;
}

.handle a {
  display: block;
  text-decoration: none;
}

.list-group-item .centence {
  padding: 0px 50px;
}

.user {
  font-size: 22px;
}
</style>

總結:

父組件 List.vue 向子組件 Item.vue 傳遞數據comment

在此說明一下props與data中屬性的區別:

子組件中的data數據,不是通過父組件傳遞的是子組件私有的,是可讀可寫的。

子組件中的所有 props中的數據,都是通過父組件傳遞給子組件的,是隻讀的。

  1. 子組件Item.vue聲明瞭comment屬性(在props中聲明(在data中聲明的話不可用))
  2. 父組件在使用Item組件的時候通過 ‘:comment’ 傳遞數據
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章