父传子
子组件代码:
<template>
<!-- 绑定按钮的内容和样式,从父组件传 type 和 btnContent -->
<button :class="type">{{btnContent}}</button>
</template>
<script>
export default {
//将需要从父组件中传的参数写在props中
props: {
btnContent: {
type: String,
default: ''
},
type: {
type: String,
default: ''
}
}
}
</script>
/*定义按钮的基本样式*/
<style scoped lang="less">
button {
position:relative;
display:block;
width: 250px;
margin-top: 20px;
text-align: center;
padding: 10rpx 0;
letter-spacing: 4rpx;
margin: 40rpx auto 0;
box-sizing:border-box;
font-size:18px;
text-decoration:none;
line-height:2.55555556;
border-radius:5px;
-webkit-tap-highlight-color:transparent;
overflow:hidden;
}
/*按钮绑定的样式 type的值为black/white时显示对应的样式*/
.black {
background-color: #2D2D2D;
color: white;
&:active {
background: #000;
}
}
.white {
background-color: #fff;
color: #000;
border: 1px solid #999;
&:active {
background: #eee;
}
}
</style>
父组件代码:
<template>
//在子组件标签内赋值(也可以绑定data数据赋值)
<b-button btnContent="点我点我" type="white"></b-button>
</template>
<script>
//引入子组件
import bButton from "@/components/bButton"
export default {
components: {
bButton
},
}
</script>
子传父
子组件代码:
<template>
<!-- 注册点击事件 点击按钮时传值给父组件 -->
<button @click="passing">{{btnContent}}</button>
</template>
<script>
export default {
data(){
return {
btnContent: '点我点我'
}
},
methods: {
passing() {
//$emit 可传多个数据/对象等
//parentEvent为自定义事件
this.$emit("parentEvent",this.btnContent)
}
}
}
</script>
父组件代码:
<template>
<b-button @parentEvent=“getVal”></b-button>
</template>
<script>
//引入子组件
import bButton from "@/components/bButton"
export default {
components: {
bButton
},
methods: {
//带参数,参数为$emit传递过来的值
getVal(para) {
console.log(para) //点我点我
}
}
}
</script>