vue的this.$emit和props的用法
vue的this.$emit和props的用法
vue组件数据传递:
1.父组件传递给子组件:在父组件引用的子组件标签上增加属性就可以传递,子组件在props: {父子间属性名称:数据类型}中接收
2.子组件监听父组件方法 ,使用this.$emit()触发父组件属性
以vue的公共头部为例
父组件
App.vue父组件,引用子组件nav-header。属性headData属性
<template>
<div id='app'>
<nav-header :headData="headData" ></nav-header>
<router-view @headFun="headFun" ></router-view>
</div>
</template>
<script>
import NavHeader from '@/components/NavHeader'
export default {
name: 'app',
components: {
NavHeader
},
data() {
return {
headData: [],
}
},
mounted() {
},
methods: {
headFun(data){
//data是App.vue的子组件通过this.$emit触发他的headFun函数传过来的值
this.headData=data;
}
}
}
</script>
子组件 通过props接收父组件App.vue的参数
<template>
<div>
<header class="ui-header is-fixed" v-show="hidshow">
<div class="ui-header-left">
<i class="mint-toast-icon mintui mintui-back" v-if="headData.goIcon==true"></i>
</div>
<span class="ui-head-title">{
{headData.title}}</span>
<div class="ui-header-right">
<img src="" alt="" v-if="headData.cartIcon==true">
<img src="" alt="" v-if="headData.perIcon==true">
<i class="mint-toast-icon mintui mintui-more" v-if="headData.moreIcon==true"></i>
</div>
</header>
</div>
</template>
<script>
export default {
name: "CityAlphabet",
props: ['headData'],
computed: {
},
data() {
return {
hidshow: false
}
},
methods: {
}
}
</script>
<style scoped>
.ui-header .is-fixed{top:0;left :0;right:0;position: fixed;z-index: 1}
.ui-header{width:100%;height:50px;line-height:50px;text-align:center;background-color:#d23a27;box-sizing: border-box;color: #fff;font-size: 17px;position: relative;}
.mintui{font-size: 25px;display: inline-block;}
.ui-head-left{position: absolute;left: 0;top: 0;bottom: 0;padding: 0 10px;}
.ui-head-right{position: absolute;right: 0;top: 0;bottom: 0;padding: 0 10px;display: -webkit-box;line-height: 50px;padding-top: 10px;}
.ui-head-right i{color: #fff;}
.ui-head-right .cart-img{width: 30px;height: 30px;}
</style>
另一个相对于App.vue子组件 利用this.$emit去触发父组件中的headFun函数
<template>
<div>
</div>
</template>
<script>
export default {
name: "home",
computed: {
},
data() {
return {
}
},
mounted(){
this.$emit("headFun",
{
title:'表通',
goback:'',
perIcon:true,
cartIcon:true,
moreIcon:false
})
},
methods: {
}
}
</script>
借鉴//blog.csdn.net/yang1393214887/article/details/104871682
还没有评论,来说两句吧...