Vue组件间相互通信(一)

6 篇文章 0 订阅
父组件向子组件传值
流程:
1、父组件中引入子组件
2、在父组件中通过v-bind绑定属性
3、子组件中通过props获取到父组件传递的值
//父组件
<template>
  <div class='father' id="app">
    <input type="text" v-model="fathermsg">
    <h3>这里是父组件</h3>
    <children v-bind:msg='fathermsg'></children>//注册Children子组件;v-bind绑定fathermsg挂载到msg
  </div>
</template>
<script>
import children from './Children.vue'//引用子组件
export default {
  data () {
    return {
      fathermsg: '父组件向子组件传递的值
    }
  },
  components: { children }//定义一个局部子组件
}
</script>
//子组件
<template>
  <div class='children'>
    <h3>这里是子组件</h3>
    <input type="text" v-model="msg"/>//显示父组件传递的值
  </div>
</template>
<script>
export default {
  props: {
    msg: {//msg 接收父组件传递的值,并做了Prop验证必填的字符串
      type: String,
      required: true
    }
  },
  methods: {
  }
}
</script>
<style lang="less" scoped>
.children{
  background-color: aquamarine
}
</style>

上述例子是由父组件的fathermsg通过v-bind绑定挂载到msg上,子组件通过props中的msg(与父组件挂载的变量名称一致)获取,从而实现父组件传值到子组件中

注:通过props向子组件传值的方式属于单方向传递,子组件无法根据传递参数的更改影响父组件

子组件向父组件传值(自定义事件)
流程:
1、在父组件中引入子组件
2、在子组件中$emit()触发父组件的事件
3、父组件在使用子组件的位置使用$on()进行监听子组件触发的事件

子:this.$emit(“function”,param); //其中function为父组件定义函数,param为需要传递参数

//父组件
<template>
  <div class='father' id="app">
    {{count}}----------{{total]}
    //v-on监听子组件$emit()触发的事件,v-on以下用@简写
    <children @fatherCounter='fatherCounter'></children>
    <children @fatherCounter='fatherCounter'></children>
  </div>
</template>
<script>
import children from './Children.vue'
export default {
  data () {
    return {
      count: 0,
      total: ''
    }
  },
  methods: {
  //fatherCounter为子组件触发的父组件方法,params为子组件传递的参数
    fatherCounter (params) {
      this.count++
      this.total = params
    }
  },
  components: { children }
}
</script>
<style scoped>
</style>
//子组件
<template>
  <div class='children'>
    <input type="button" @click="clickCounter" :value="count">
  </div>
</template>
<script>
export default {
  props: {
  },
  data () {
    return {
      count: 0
    }
  },
  methods: {
    clickCounter () {
      this.count++
      let params = '子组件向父组件传递的值'
      this.$emit('fatherCounter', params)//触发事件,并传递了一个参数
    }
  }
}
</script>
<style lang="less" scoped>
.children{
  background-color: aquamarine
}
</style>

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Echo___Echo

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值