prop----父組件向子組件傳遞數(shù)據(jù)。如自定義標題和內(nèi)容
$ref----父組件調(diào)用子組件的屬性和方法。
$emit----
Prop使用
父組件動態(tài)的向子組件傳遞數(shù)據(jù)。利用props給子組件定義屬性,在父組件給屬性賦值就能使子組件也具有同樣的值。
//父組件main.vue
<template>
<div>
<img src="../../assets/img.jpeg">
<h1>主頁內(nèi)容</h1>
<child postCont="我是子內(nèi)容"></child><!--靜態(tài)傳遞數(shù)據(jù)-->
<child :postCont="msg"></child><!--動態(tài)傳遞數(shù)據(jù)-->
</div>
</template>
<script>
import Child from './child'
export default {
name: "main",
components:{
Child
},
data() {
return {
msg:'我是子內(nèi)容'
}
}
}
</script>
//子組件child.vue
<template>
<div>
<h3>{{postCont}}</h3>
</div>
</template>
<script>
export default {
name: "child",
props:[
'postCont'//自定義的屬性名稱
]
}
</script>
$ref使用
ref就相當于在父組件中給子組件命名一個id,this.$refs.childid就能獲取子組件,然后使用子組件的方法或者獲取屬性。
//父組件index.vue
<template>
<div>
<img src="../../assets/img.jpeg">
<h1>我是主頁面</h1>
<child ref="childid"></child>
</div>
</template>
<script>
import Child from './child'
export default {
name: "index",
components:{
Child
},
mounted(){
console.log(this.$refs.childid);
this.$refs.childid.setMessage('我是子組件!');
}
}
</script>
//子組件
<template>
<div>
<h3>{{message}}</h3>
</div>
</template>
<script>
export default {
name: "child",
data() {
return {
message:''
}
},
methods: {
setMessage(msg) {
this.message = msg;
}
}
}
</script>
$emit使用
子組件調(diào)用到父組件的方法。
//父組件index.vue
<template>
<div>
<img src="../../assets/img.jpeg">
<h1>我是父組件</h1>
<child @close="show" v-show="isShow"></child>
</div>
</template>
<script>
import Child from './child'
export default {
name: "index",
components: {
Child
},
data() {
return {
message: '',
isShow:false
}
},
methods:{
show(參數(shù)){
this.isShow = !this.isShow;
}
}
}
</script>
//子組件child.vue
<template>
<div>
<h3 class="msg">{{msg}}</h3>
<button @click=hidden>點擊顯示子組件</button>
</div>
</template>
<script>
export default {
name: "child",
data() {
return {
msg: '我是子組件'
}
},
methods: {
hidden: function () {
this.$emit('close', 參數(shù)) //對應父組件標簽@close
}
}
}
</script>