vue子组件与父组件通讯

说明

因为购物车的细节比较多,但是实现方法又何前面类似,只是繁琐了一些,因此我就不再一一记录,只记录一些相关的知识点。

知识点

this.$emit(“method”)

先把场景搭建好:有两个vue组件,分别为CartItem.vue和Cart.vue,其中CartItem是子组件,Cart是CartItem的父组件。

  1. 组件关系声明:
    那代码怎么说明这个关系呢?就是在父组件Cart中的components部分声明:
components:{
   CartItem,
}
  1. 子组件发起通讯请求:
    子组件的script中使用this.$emit(“method”)来发起动作请求,其中method被绑定到父组件中:
this.$emit("change_select")
  1. 父组件接受动作请求,并调用对应方法:
    在父组件template中,会用@来修饰这个change_select,并绑定对应的方法,当子组件发出请求时,父组件就执行:
<CartItem :key="key" v-for="(course,key) in course_list" @change_select="calc_total" :course="course"></CartItem>

//script中:
calc_total(){
  let total = 0;
  this.course_list.forEach((course,key)=>{
    if(course.selected){
      total += parseFloat( course.price );
    }
  });
  this.total_price = total;
}

以上三个步骤便完成了子组件与父组件的通讯过程。

TIPS

值得注意的是这段代码:

<CartItem :key="key" v-for="(course,key) in course_list" @change_select="calc_total" :course="course"></CartItem>

里面的:course="course",这里是将Cart组件里面的course属性,以“course”的名字传到子组件中去,这样,子组件就能够使用父组件的数据了。子组件使用props来接收这个属性,且props是子组件访问父组件数据的唯一接口,且props是单向数据绑定,即数据流为父组件到子组件。子组件具体代码如下:

<script>
export default {
	...
	props:["course"],
	...
}

forEach

javascript中循环遍历数组的方法

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 中,组件组件之间可以通过事件通信。 组件组件传递数据,可以通过 props 属性实现。而组件组件传递数据,则可以通过事件的方式实现。 具体实现方法如下: 1. 组件组件传递数据 在组件中,通过 props 属性将数据传递给组件: ```html <template> <div> <child-component :message="message"></child-component> </div> </template> <script> import ChildComponent from './ChildComponent.vue' export default { components: { ChildComponent }, data() { return { message: 'Hello world!' } } } </script> ``` 在组件中,接收组件传递的数据: ```html <template> <div>{{ message }}</div> </template> <script> export default { props: { message: { type: String, default: '' } } } </script> ``` 2. 组件组件传递数据 在组件中,通过 $emit() 方法触发事件,将数据传递给组件: ```html <template> <button @click="sendMessage">发送消息</button> </template> <script> export default { methods: { sendMessage() { this.$emit('send-message', 'Hello world!') } } } </script> ``` 在组件中,通过 v-on 指令监听组件触发的事件,并在事件处理函数中获取组件传递的数据: ```html <template> <div> <child-component @send-message="handleMessage"></child-component> </div> </template> <script> import ChildComponent from './ChildComponent.vue' export default { components: { ChildComponent }, methods: { handleMessage(message) { console.log(message) // 输出:Hello world! } } } </script> ``` 以上就是 Vue组件组件之间通过事件通信的方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值