一、父組件向子組件傳值
方法一:通過props傳值
1.創(chuàng)建子組件渠脉,在src/components/文件夾下新建一個child.vue
2.在child.vue 中創(chuàng)建props,然后新加一個title屬性
<template>
<div>
<h1>child子組件</h1>
<div>{{title}}</div>
</div>
</template>
<script>
export default { name: 'child', props:["title"],}
</script><style scoped lang="less">
</style>
3.在parent.vue父組件中注冊child組件宇整,并在template中加入child標簽,標簽中綁定title屬性芋膘,并在data中賦值
<template>
<div>
<h1>parent父組件</h1>
<child v-bind:title="parentTitle"></child>
</div>
</template>
<script>import child from './child';//引用子組件export default { name: 'parent', data(){ return
{ parentTitle:"hello,child" }
}, components:{ child }}
</script>
<style scoped lang="less"></style>
父組件向子組件傳值總結:
子組件在props中創(chuàng)建一個屬性鳞青,用以接收父組件傳過來的值
父組件中注冊子組件
在子組件標簽中添加子組件props中創(chuàng)建的屬性
把需要傳給子組件的值賦給該屬性
方法二:通過ref屬性,父組件調用子組件的方法索赏,把要傳的值作為參數(shù)傳給子組件盼玄,子組件獲取該參數(shù)贴彼,并使用
子組件代碼
<template>
<div>
<h1>child子組件</h1>
<div>{{num}}</div>
</div>
</template>
<script>
export default { name: 'child', props:["title"],
data(){ return { isshow:true, num:0, }
}, methods:{ getVal(val){ this.num = val; }
}}
</script>
<style scoped lang="less">
</style>
父組件代碼
<template>
<div>
<h1>parent父組件</h1>
<child ref="childnode">
</child>
</div>
</template>
<script>import child from './child';//引用子組件export default {
name: 'parent', data()
{ return {
num:100
}
}, components:{
child },
mounted(){
this.init();
},
methods:{
init(){
//獲取子組件屬性
this.isshow = this.$refs.childnode.isshow;
console.log("isshow:"+this.isshow);
//父組件調用子組件方法潜腻,傳值給子組件 this.$refs.childnode.getVal(this.num);
}, }}</script><style scoped lang="less">
</style>
二、子組件向父組件傳值
1.在子組件中創(chuàng)建一個按鈕器仗,給按鈕綁定一個點擊事件
2.在響應該點擊事件的函數(shù)中使用$emit
來觸發(fā)一個自定義事件融涣,并傳遞一個參數(shù)
<template>
<div>
<h1>child子組件</h1>
<button @click="sendMsgToParent">向父組件傳值</button>
</div>
</template>
<script>export default {
name: 'child', methods:{
sendMsgToParent(){ this.$emit("listenToChildEvent","this message is from child")
}
}}
</script>
<style scoped lang="less"></style>
3.在父組件中的子標簽中監(jiān)聽該自定義事件并添加一個響應該事件的處理方法
<template>
<div>
<h1>parent父組件</h1>
<child v-on:listenToChildEvent="showMsgFromChild"></child>
</div></template><script>import child from './child';//引用子組件export default {
name: 'parent', data(){
},
components:{ child
}, methods:{
showMsgFromChild(msg)
{ console.log(msg) }
}
}
</script>
<style scoped lang="less"></style>
子組件向父組件傳值總結:
子組件中需要以某種方式例如點擊事件的方法來觸發(fā)一個自定義事件
將需要傳的值作為
$emit
的第二個參數(shù),該值將作為實參傳給響應自定義事件的方法在父組件中注冊子組件并在子組件標簽上綁定對自定義事件的監(jiān)聽
總之精钮,在通信中威鹿,無論是子組件向父組件傳值還是父組件向子組件傳值,他們都有一個共同點就是有中間介質轨香,子向父的介質是自定義事件忽你,父向子的介質是props中的屬性或者借助子組件的ref屬性。
image