父组件向子组件传值
子组件中的内容
<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>
父组件中的内容
<template>
<div class="tabbarWrap">
<Item txt="首页" src="../../static/img/1.png"></Item>
<Item txt="购物车" 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>
重点:
props的使用
与data一样,props 可以用在模板中
可以在vm实例中像this.message这样使用
与组件data函数return的数据区别
props的数据来自父级
data中数据是组件自己的数据
效果图:
image.png
子组件向父组件传值
子组件中的内容
<template>
<div>
<!--点击的时候向父组件传值-->
<h1 @click="fn">
{{childmsg}}
点击我向父组件传值
</h1>
</div>
</template>
<script>
export default {
name: "child",
data:function () {
return {
childmsg:"子组件里面的信息",
msg:"子组件里传递的值"
}
},
methods:{
fn:function () {
//向子组件传值
this.$emit("change",this.msg)
}
}
}
</script>
父组件中的内容
<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>
image.png
点击子组件的文字后
image.png