\components\pageHead\pageHead.vue
<template>
<view>
{{item.title}}---{{item.detail}}
<button type="default" @click="handleBtn">修改</button>
</view>
</template>
<script>
export default {
name: "pageHead",
props: {
item:{
title:"",
detail:""
},
},
methods: {
handleBtn() {
this.$emit('handleBtn')
}
},
}
</script>
注意:在components右键创建component,name是自动生成的,需要选中同时创建同名目录
props中可以放置对象或者数组…
this.$emit是一个事件触发器,可以带参数
<template>
<div>
<pageHead :item="item" @handleBtn="handleBtn"></pageHead>
</div>
</template>
<script>
export default {
data() {
return {
item: {
title: "hello",
detail: "你好"
}
}
},
methods: {
handleBtn() {
console.log('handleBtn');
}
},
}
</script>
总结:1.props父传子,
<my-com :btnName="333" @ClickBTN="ClickBTN"></my-com>
:btnName="333"父组件上以属性绑定的样式进行接口定义
在子组件中vprops中定义btnName,类似data进行数据绑定
2.emit子传父
<my-com :btnName="333" @ClickBTN="ClickBTN"></my-com>
在父组件上以事件绑定的方式进行事件挂载,同时在父组件methods中定义ClickBTN方法实现,
<button type="default" @click="ClickBTN">{{btnName}}</button>
ClickBTN() {
this.$emit("ClickBTN",this.btnName)
}
在子组件中定义事件触发条件,用this.$emit触发父组件@ClickBTN="ClickBTN"的ClickBTN方法
//components\card\card.vue
<template>
<view>
<view :style="{background:color}" >
hello
</view>
<image src="../../static/logo.png" @click="handleClick"></image>
</view>
</template>
<script>
export default {
name: "card",
props: {
color: {
type: String,
default: "white"
},
},
methods: {
handleClick() {
console.log("子组件的事件......");
this.$emit("handleClick",123)
}
},
}
</script>
<template>
<view class="content">
<card @handleClick="handleClick"></card>
<card :color="color"></card>
<card color="red"></card>
<card ></card>
</view>
</template>
<script>
export default {
data() {
return {
color: 'yellow'
}
},
methods: {
handleClick(e) {
console.log("父组件的事件......",e);
}
}
}
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
</style>
//父组件传值props
<card color="red"></card>
<card :color="color"></card>
<card></card>
//components\card\card.vue
//自定义组件接受props vprops
props: {
color: {
type: String,
default: "white"
},
}
//emit
//父组件注册handleClick事件
<card @handleClick="handleClick"></card>
//父组件定义handleClick事件实现方法,可不同名
methods: {
handleClick(e) {
console.log("父组件的事件......",e);
}
}
//自定义组件触发this.$emit("handleClick",123)
//触发handleClick事件(已经注册到父组件中)
handleClick() {
console.log("子组件的事件......");
this.$emit("handleClick",123)
}