父組件向子組件傳值
子組件中的內(nèi)容
<template>
<div class="itemWrap">
<img :src="src" alt="">
<!--<img src="../../static/img/1.png" alt="">-->
<span>{{txt}}</span>
</div>
</template>
<script>
export default {
name: "child",
props:["src","txt"],
}
</script>
<style scoped>
.itemWrap{
width: 25%;
height: 100%;
}
.itemWrap img{
width: 50%;
height: 2rem;
display: block;
margin: 0.5rem auto 0 auto;
}
</style>
父組件中的內(nèi)容
<template>
<div class="tabbarWrap">
<Item txt="首頁(yè)" src="../../static/img/1.png"></Item>
<Item txt="購(gòu)物車" src="../../static/img/2.png"></Item>
<Item txt="收藏" src="../../static/img/3.png"></Item>
<Item txt="逛逛" src="../../static/img/4.png"></Item>
</div>
</template>
<script>
import Item from './item'
export default {
name: "tabbar",
components:{
Item
}
}
</script>
<style scoped>
*{margin: 0;padding: 0}
.tabbarWrap{
width: 100%;
height: 5rem;
background: ghostwhite;
display: flex;
justify-content: center;
align-items: center;
position: fixed;
bottom: 0;
left: 0;
}
</style>
重點(diǎn):
props的使用
與data一樣昧辽,props 可以用在模板中
可以在vm實(shí)例中像this.message這樣使用
與組件data函數(shù)return的數(shù)據(jù)區(qū)別
props的數(shù)據(jù)來自父級(jí)
data中數(shù)據(jù)是組件自己的數(shù)據(jù)
效果圖:
子組件向父組件傳值
子組件中的內(nèi)容
<template>
<div>
<!--點(diǎn)擊的時(shí)候向父組件傳值-->
<h1 @click="fn">
{{childmsg}}
點(diǎn)擊我向父組件傳值
</h1>
</div>
</template>
<script>
export default {
name: "child",
data:function () {
return {
childmsg:"子組件里面的信息",
msg:"子組件里傳遞的值"
}
},
methods:{
fn:function () {
//向子組件傳值
this.$emit("change",this.msg)
}
}
}
</script>
父組件中的內(nèi)容
<template>
<div>
<h1>父組件</h1>
<h3>{{parentmsg}}</h3>
<!--接受傳遞的值-->
<child @change="getVal"></child>
<input type="text" v-model="getmsg">
</div>
</template>
<script>
import Child from './child'
export default {
name: "father",
data:function () {
return{
parentmsg:"父組件里面的信息!",
getmsg:""
}
},
components: {
Child
},
methods:{
getVal:function (val) {
console.log(val)//拿到的值
this.getmsg=val
}
}
}
</script>
點(diǎn)擊子組件的文字后