父子組件通信
有可能在一個頁面中,我們從服務器請求到了很多數據,其中一部分的數據並非是在我們的大組件中展示的,而是需要在其子組件進行展示。但是子組件並不會再次發送一個網絡請求(發送請求對服務器壓力大),而是直接將父組件中的數據傳遞給子組件
注意:在開發中,Vue實例和子組件的通信和父組件與子組件的通信過程是一樣的,所以以下示例通過Vue實例和子組件的通信來解釋說明
父子組件通信—父傳子
通過 props(properties)向子組件傳遞數據,使用props來聲明需要從父組件那裏接收的數據,這裏介紹兩種方式
第一種方式------字符串數組
第一種方式是使用字符串數組,數組中的字符串就是傳遞時的名稱(子組件中的變量名)
注意:
(1)一定要使用v-bind綁定父組件中的變量
(2)不使用v-bind,會將message、books當作一個字符串
(3)具體步驟看註釋
<body>
<div id="app">
<cpn book="books" cmessage="message"></cpn>
//父傳子
<cpn :book="books" :cmessage="message"></cpn>
</div>
//模板
<template id="cpn">
<div>
<ul>
<li v-for="item in book">{{item}}</li>
</ul>
<h2>{{cmessage}}</h2>
</div>
</template>
<script src="../vue.js"></script>
<script>
const cpn = {
template:"#cpn",
//使用字符串數組
props:["cmessage","book"]
}
//父組件
const app = new Vue({
el:'#app',
data:{
message:"hello vue",
books:["紅樓夢","水滸傳","三國演義","西遊記"]
},
//子組件
components:{
cpn
}
})
</script>
</body>
第二種方式------對象
第一種方式是使用對象,對象可以設置傳遞時的類型,也可以設置默認值,還有是否必傳等。
注意:
(1)提供默認值只有在組件中沒有使用v-bind綁定父組件中的值時,顯示默認值
(2) 高版本Vue中類型是對象或函數時,默認值必須是一個函數
(3)require爲true時,父組件必須向子組件傳值(使用v-bind),否則報錯
類型限制
const cpn = {
template:"#cpn",
props: {
//單個類型限制
cmessage:String,
//多個類型限制
book:[Number,String]
}
}
提供默認值
使用default,當沒有使用v-bind綁定父組件中的值時,顯示默認值
const cpn = {
template:"#cpn",
props: {
book:{
type: Array,
//高版本Vue
default(){
return []
}
cmessage:{
type: String,
//默認值是父組件沒有向子組件傳值纔會顯示
default:"hello",
}
}
是否必傳
使用require(布爾型),爲true表示父組件必須向子組件傳的值,若沒有傳,則會報錯
const cpn = {
template:"#cpn",
props: {
book:Array,
cmessage:{
type: String,
//布爾值,父組件必須向子組件傳的值,否則報錯
require:true
}
}