Vue父子組件之間的傳遞數(shù)據(jù)和方法調(diào)用
概述
在一個良好定義的接口中盡可能將父子組件解耦是很重要的,因此組件實例的作用域必須是獨立的。這意味著不能 (也不應(yīng)該) 在子組件的模板內(nèi)直接引用父組件的數(shù)據(jù),也不能在父組件的模板中直接使用子組件的數(shù)據(jù)雄嚣,否則會增強(qiáng)組件之間的耦合性急但,使得組件不利于維護(hù)和管理。在 Vue 中琅绅,父子組件的關(guān)系可以總結(jié)為 props down, events up。父組件通過 props 向下傳遞數(shù)據(jù)給子組件谱俭,子組件通過 events 給父組件發(fā)送消息奉件。
Vue組件選項props-父組件向子組件傳遞數(shù)據(jù)
1.靜態(tài)props
子組件要顯式地用 props 選項聲明它期待獲得的數(shù)據(jù)
const childNode = {
template: '<div>{{message}}</div>',
props:['message']//子組件要顯式地用 props 選項聲明它期待獲得的數(shù)據(jù)
}
靜態(tài)props通過為子組件在父組件中的 占位符添加特性的方式 來達(dá)到傳值的目的
<div id="example">
<parent></parent>
</div>
<script>
const childNode = {
template: '<div>{{message}}</div>',
props:['message']
}
const parentNode = {
template: `
<div class="parent">
<child message="aaa"></child>
<child message="bbb"></child>
</div>`,
components: {
childNode
}
};
// 創(chuàng)建根實例
new Vue({
el: '#example',
components: {
parentNode
}
})
</script>
2.命名規(guī)定
對于props聲明的屬性來說,在父級HTML模板中昆著,屬性名一般需要使用中劃線寫法县貌,子級props屬性聲明時,使用小駝峰或者中劃線寫法都可以凑懂;而子級HTML模板使用從父級傳來的變量時煤痕,需要使用對應(yīng)的小駝峰寫法
const parentNode = {
template: `
<div class="parent">
<child my-message="aaa"></child>//父級HTML模板中,屬性名一般使用中劃線寫法
<child my-message="bbb"></child>
</div>`,
components: {
childNode
}
};
const childNode = {
template: '<div>{{myMessage}}</div>',//子級HTML模板使用從父級傳來的變量時接谨,需要使用對應(yīng)的小駝峰寫法
props:['myMessage']//子級props屬性聲明時摆碉,使用小駝峰
//props:['my-message']//子級props屬性聲明時,中劃線
}
3.動態(tài)props
在模板中脓豪,要動態(tài)地綁定父組件的數(shù)據(jù)(父組件data里面的變量)到子模板的 props巷帝,與綁定到任何普通的HTML特性相類似,就是用 v-bind(簡寫:)扫夜。每當(dāng)父組件的數(shù)據(jù)變化時楞泼,該變化也會傳導(dǎo)給子組件
const childNode = {
template: '<div>{{myMessage}}</div>',
props:['myMessage']
}
const parentNode = {
template: `
<div class="parent">
<child :my-message="data1"></child>
<child :my-message="data2"></child>
</div>`,
components: {
childNode
},
data(){
return {
'data1':'aaa',
'data2':'bbb'
}
}
};
思考:如何傳遞一個number類型的數(shù)字(1.:message='1',2:message='num' num:1,靜態(tài)props默認(rèn)傳遞的是字符串類型)
4.props驗證
可以為組件的 props 指定驗證規(guī)格。如果傳入的數(shù)據(jù)不符合規(guī)格笤闯,Vue會發(fā)出警告堕阔。當(dāng)組件給其他人使用時,這很有用颗味,要指定驗證規(guī)格超陆,props需要用對象的形式,而不能用上述的字符串?dāng)?shù)組了浦马。
Vue.component('example', {
props: {
// 基礎(chǔ)類型檢測 (`null` 意思是任何類型都可以)
propA: Number,
// 多種類型
propB: [String, Number],
// 必傳且是字符串
propC: {
type: String,
required: true
},
// 數(shù)字时呀,有默認(rèn)值
propD: {
type: Number,
default: 100
},
// 數(shù)組/對象的默認(rèn)值應(yīng)當(dāng)由一個工廠函數(shù)返回
propE: {
type: Object,
default: function () {
return { message: 'hello' }
}
},
// 自定義驗證函數(shù)
propF: {
validator: function (value) {
return value > 10
}
}
}
})
type可驗證:String、Number捐韩、Boolean退唠、Function、Object荤胁、Array、Symbol
type 也可以是一個自定義構(gòu)造器函數(shù)屎债,使用 instanceof 檢測
propSomeProperty:{
type(value){
return value instanceof Person
}
}
當(dāng) prop 驗證失敗仅政,Vue 會在拋出警告 (如果使用的是開發(fā)版本)垢油。props會在組件實例創(chuàng)建之前進(jìn)行校驗,所以在函數(shù)驗證里圆丹,組件還沒創(chuàng)建滩愁,諸如 data、computed 或 methods 等實例屬性還無法使用辫封。
5.單向數(shù)據(jù)流
prop 是單向綁定的:當(dāng)父組件的屬性變化時硝枉,將傳導(dǎo)給子組件,但是不會反過來倦微。這是為了防止子組件無意修改了父組件的狀態(tài)——這會讓應(yīng)用的數(shù)據(jù)流難以理解妻味。另外,每次父組件更新時欣福,子組件的所有 prop 都會更新為最新值责球。這意味著不應(yīng)該在子組件內(nèi)部改變 prop。如果這么做了拓劝,Vue 會在控制臺給出警告雏逾。
<div id="example">
<parent></parent>
</div>
<script>
var childNode = {
template: `
<div class="child">
<div>
<span>子組件數(shù)據(jù)</span>
<input v-model="childMsg">
</div>
<p>{{childMsg}}</p>
</div>
`,
props:['childMsg']
}
var parentNode = {
template: `
<div class="parent">
<div>
<span>父組件數(shù)據(jù)</span>
<input v-model="msg">
</div>
<p>{{msg}}</p>
<child :child-msg="msg"></child>
</div>
`,
components: {
'child': childNode
},
data(){
return {
'msg':'match'
}
}
};
// 創(chuàng)建根實例
new Vue({
el: '#example',
components: {
'parent': parentNode
}
})
</script>
父組件數(shù)據(jù)變化時,傳遞給子組件的數(shù)據(jù)會相應(yīng)變化郑临;而子組件改變父組件傳遞的數(shù)據(jù)時栖博,父組件數(shù)據(jù)不變,并在控制臺顯示警告
6.修改prop數(shù)據(jù)
修改prop中的數(shù)據(jù)厢洞,通常有以下兩種原因
- prop 作為初始值傳入后仇让,子組件想把它當(dāng)作局部數(shù)據(jù)來用
- prop 作為初始值傳入,由子組件處理成其它數(shù)據(jù)輸出
[注意]JS中對象和數(shù)組是引用類型犀变,指向同一個內(nèi)存空間妹孙,如果 prop 是一個對象或數(shù)組,在子組件內(nèi)部改變它會影響父組件的狀態(tài).
對于這兩種情況获枝,正確的應(yīng)對方式是
1蠢正、子組件定義一個局部變量,并用 prop 的值初始化它
props: ['initialCounter'],
data: function () {
return { counter: this.initialCounter }
}
示例代碼:
<div id="example">
<parent></parent>
</div>
<script src="https://unpkg.com/vue"></script>
<script>
var childNode = {
template: `
<div class="child">
<div>
<span>子組件數(shù)據(jù)</span>
<input v-model="temp">
</div>
<p>{{temp}}</p>
</div>
`,
props:['childMsg'],
data(){
return{
temp:this.childMsg
}
},
};
var parentNode = {
template: `
<div class="parent">
<div>
<span>父組件數(shù)據(jù)</span>
<input v-model="msg">
</div>
<p>{{msg}}</p>
<child :child-msg="msg"></child>
</div>
`,
components: {
'child': childNode
},
data(){
return {
'msg':'match'
}
}
};
// 創(chuàng)建根實例
new Vue({
el: '#example',
components: {
'parent': parentNode
}
})
</script>
缺點:父組件數(shù)據(jù)發(fā)生變化是省店,子組件無法實時更新到
2嚣崭、定義一個計算屬性,處理 prop 的值并返回
props: ['size'],
computed: {
normalizedSize: function () {
return this.size懦傍;
}
}
但是堤结,由于是計算屬性,則只能顯示值箫荡,設(shè)置值相對麻煩锥忿,也可以做到(set,get)
props: ['size'],
computed: {
normalizedSize:{
get(){
return this.size;
},
set(value){
this.size = value
}
}
}
3.利用watch監(jiān)聽
<div id="example">
<parent></parent>
</div>
<script src="https://unpkg.com/vue"></script>
<script>
var childNode = {
template: `
<div class="child">
<div>
<span>子組件數(shù)據(jù)</span>
<input v-model="temp">
</div>
<p>{{temp}}</p>
</div>
`,
props:['childMsg'],
data(){
return{
temp:this.childMsg
}
},
watch:{
childMsg(){
this.temp = this.childMsg
}
}
};
var parentNode = {
template: `
<div class="parent">
<div>
<span>父組件數(shù)據(jù)</span>
<input v-model="msg">
</div>
<p>{{msg}}</p>
<child :child-msg="msg"></child>
</div>
`,
components: {
'child': childNode
},
data(){
return {
'msg':'match'
}
}
};
// 創(chuàng)建根實例
new Vue({
el: '#example',
components: {
'parent': parentNode
}
})
</script>
子組件調(diào)用父組件的方法
1.直接在子組件中通過this.$parent.event來調(diào)用父組件的方法
父組件
<template>
<div>
<child></child>
</div>
</template>
<script>
import child from '@/components/dam/child';
export default {
components: {
child
},
methods: {
//父組件方法
fatherMethod() {
console.log('測試');
}
}
};
</script>
子組件
<template>
<div>
<button @click="childMethod">點擊可調(diào)用父組件方法</button>
</div>
</template>
<script>
export default {
methods: {
childMethod() {
this.$parent.fatherMethod();
}
}
};
</script>
2.在子組件里用$emit向父組件觸發(fā)一個事件,父組件監(jiān)聽這個事件就行了(常用)
父組件
<template>
<div>
<!-- fatherMethod:出發(fā)父組件方法的命名規(guī)定 --!>
<child @fatherMethod="fatherMethod"></child>
</div>
</template>
<script>
import child from '~/components/dam/child';
export default {
components: {
child
},
methods: {
fatherMethod(params) {
//params:父組件接受子組件傳來的參數(shù)
console.log(params);
}
}
};
</script>
子組件
<template>
<div>
<button @click="childMethod">點擊</button>
</div>
</template>
<script>
export default {
methods: {
childMethod() {
//params:子組件傳遞給父組件的參數(shù)
//fatherMethod:子組件觸發(fā)父組件方法的命名規(guī)定
this.$emit('fatherMethod',params);
}
}
};
</script>
注意:這種方法也是子組件傳遞數(shù)據(jù)給父組件的方式
3.父組件把方法傳入子組件中签财,在子組件里直接調(diào)用這個方法(利用子組件的props屬性)
//子組件
const Child = {
props:{
parentMethod:{
type:Function,
default:null
}
},
template:`
<div>
<button @click="parentMethod">調(diào)用父組件方法</button>
</div>
`,
mounted(){
console.log(this.parentMethod);
}
};
//父組件
const Parent = {
components:{
Child
},
template:`
<div>
<child :parentMethod="alertSomeData"></child>
</div>
`,
methods:{
alertSomeData(){
alert('我是父組件方法');
}
}
};
new Vue({
el:'#app',
components:{
Parent
},
template:'<Parent />'
})
子組件傳遞數(shù)據(jù)給父組件
子組件相關(guān)邏輯觸發(fā)式串慰,利用this.$emit('觸發(fā)父組件方法的標(biāo)價',傳遞給父組件的數(shù)據(jù))
//子組件
const Child = {
template:`
<div>
<button @click="emitChildData">傳遞子組件數(shù)據(jù)給父組件</button>
</div>
`,
data(){
return{
childMsg:'我是子組件數(shù)據(jù)'
}
},
methods:{
//子組件傳遞數(shù)據(jù)給父組件
emitChildData(){
this.$emit('emitDataToParent',this.childMsg);
}
}
};
//父組件
const Parent = {
components:{
Child
},
template:`
<div>
<child @emitDataToParent="getDataFromChild"></child>
<span v-text="getFromChild"></span>
</div>
`,
data(){
return{
getFromChild:''
}
},
methods:{
getDataFromChild(getData){
console.log(getData);
this.getFromChild = getData;
}
}
};
//入口組件
const App ={
components:{
Parent
},
template: `
<div>
<parent></parent>
</div>
`
};
//根組件
new Vue({
el:document.getElementById('app'),
components:{
App,
},
template:'<App />'
})
父組件調(diào)用子組件方法
子組件html用ref屬性標(biāo)記,父組件利用this.$refs.xxx.childMethods
//子組件
const Child = {
template:`
<div>
我是子組件
</div>
`,
methods:{
//子組件方法
childMethod(){
alert('我是子組件方法');
}
}
};
//父組件
const Parent = {
components:{
Child
},
template:`
<div>
<child ref="getChildMethods"></child>
<button @click="emitChildMethod">父組件調(diào)用子組件方法</button>
</div>
`,
methods:{
emitChildMethod(){
//父組件調(diào)用子組件方法
this.$refs.getChildMethods.childMethod();
}
}
};
//入口組件
const App ={
components:{
Parent
},
template: `
<div>
<parent></parent>
</div>
`
};
//根組件
new Vue({
el:document.getElementById('app'),
components:{
App,
},
template:'<App />'
})