`<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12"></script>
<title>Vue自學(xué):父子組件通信-父?jìng)髯觩rops</title>
</head>
<body>
<div id="app">
<!-- 分配通信過(guò)來(lái)的數(shù)值給到cpn子組件,分配方式為綁定虛擬屬性 v-bind:arr="arr" -->
<cpn v-bind:arr="arr"></cpn>
</div>
</body>
<template id="cpn">
<div>
<ul>
<!-- 成功的分配到了數(shù)值,通過(guò)分配過(guò)來(lái)的數(shù)值遍歷 -->
<li v-for="item in arr">{{item}}</li>
</ul>
</div>
</template>
<script type="text/javascript">
//在上一節(jié)中,我們提到了子組件是不能引用父組件或者Vue實(shí)例的數(shù)據(jù)的
//但是,在開發(fā)中,往往一些數(shù)據(jù)確實(shí)需要從上層傳遞到下層
//比如在一個(gè)頁(yè)面當(dāng)中,我們從服務(wù)器請(qǐng)求到了很多數(shù)據(jù)
//其中一部分?jǐn)?shù)據(jù),并非是我們整個(gè)頁(yè)面的大組件來(lái)展示的,而是需要下面的子組件進(jìn)行展示
//這個(gè)時(shí)候,并不會(huì)讓子組件再次發(fā)送一個(gè)網(wǎng)絡(luò)請(qǐng)求,而是直接讓大組件(父組件)傳遞數(shù)據(jù)給小組件(子組件)
//如何進(jìn)行父組件間的數(shù)據(jù)傳遞呢?Vue官方提到
//通過(guò)props向子組件傳遞數(shù)據(jù)
//通過(guò)事件向父組件傳遞信息
//1.創(chuàng)建局部組件
const cpn = {
// 設(shè)置綁定的模板
template:'#cpn',
data(){
},
methods:{
},
//props:父組件傳遞到子組件的通信
props:{
//默認(rèn)值寫法(最為完善的寫法)
//傳遞過(guò)來(lái)的是父組件中的arr屬性
//推薦使用使用對(duì)象寫法
arr:{
type:Array,
//當(dāng)默認(rèn)值為空數(shù)組時(shí),正確的是些是使用函數(shù)返回默認(rèn)值
default(){
return []
},
required:true,
},
},
//使用對(duì)象寫法的同時(shí),也可以使用數(shù)組寫法 ['arr'],但無(wú)法進(jìn)行數(shù)據(jù)驗(yàn)證,因而不推薦
//使用對(duì)象寫法,可以進(jìn)行數(shù)據(jù)類型校驗(yàn),驗(yàn)證支持如下類型:
//String
//Number
//Boolean
//Array
//Object
//Date
//Function
//Symbol
}
//2.創(chuàng)建父組件
const app = new Vue({
el:'#app',
data:{
arr:['蘋果','香蕉','雪梨','蔬菜'],
},
methods:{
},
components:{
'cpn':cpn
},
})
//使用對(duì)象的方式對(duì)類型進(jìn)行返回或驗(yàn)證
// Vue.component('my-component',{
// props:{
// //基礎(chǔ)的類型檢查('null,匹配任何類型'),匹配單個(gè)
// propA:Number,
// //匹配多個(gè)可能的類型,重疊
// propB:[string,Number],
// //必須的字符串
// propC:{
// type:String,
// required:true,
// },
// //帶有默認(rèn)值為數(shù)字的
// propD:{
// type:Number,
// default:100,
// }
// //帶有默認(rèn)值的對(duì)象
// propE:{
// type:Object,
// //對(duì)象或數(shù)組,一定以函數(shù)方式返回
// default(){
// return {
// name:'梁凱達(dá)'
// }
// }
// },
// //自定義驗(yàn)證函數(shù)
// propF:{
// validator:function(){
// //這個(gè)值必須匹配下列字符串中的某一個(gè)
// return ['success','warning','danger'].indexOf(value) !== -1
// }
// }
// }
// })
</script>
</html>`
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號(hào)
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://ipnx.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號(hào)