【Vue.js】父子组件传值

父传子

子组件代码:

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值