您的位置:首页 > Web前端 > Vue.js

【Vue.js】父子组件传值

2018-12-20 15:27 896 查看
版权声明:作者:Kamen_Yip 來源:CSDN 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。 https://blog.csdn.net/weixin_43387238/article/details/85123443

父传子

子组件代码:

<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>

vuex组件通信

https://vuex.vuejs.org/zh/guide/

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: