Vue的父子通信

一、父组件向子组件通信

使用props属性传参(父组件的数据通过参数接口传递给子组件)

1.静态传参(参数不变)

Vue.component('my-component', {
  // 像function一样,声明组件的参数名称;
  props: ['message'],
  // 传进来以后,你可以在组件下的模板中使用这个数据
  template: '<span>{{ message }}</span>'
})
var vm = new Vue({
  el: '#example'
})
<div id="example">
  <my-component message='Hello World'></my-component>//传了一个固定的hello world
</div>

2.动态传参(参数动态)

<div id='example'>
  <input v-model="parentMsg">
  <br>
  <child v-bind:my-message="parentMsg"></child>//HTML(不能使用驼峰命名)中用短横线命名,会自动转换成myMessage
</div>
 
Vue.component('child', {
  props: ['myMessage'],
  template: '<span>{{ myMessage }}</span>'
})
new Vue({
    el:'#example',
    data:{
        parentMsg:''
    }
})

v-bind:my-message=“parentMsg 就这样把一个动态响应式的参数传递给了子组件。

3.参数验证

Vue.component('example', {
  props: {
    // 基础类型检查 (`null` 表示可以接受任何类型)
    propA: Number,
    // 多个类型限定
    propB: [String, Number],
    // 必填限制
    propC: {
      type: String,
      required: true
    },
    // 默认值设置
    propD: {
      type: Number,
      default: 100
    },
    // 对象/数组 默认值需要用闭包返回
    propE: {
      type: Object,
      default: function () {
        return { message: 'hello' }
      }
    },
    // 自定义验证条件
    propF: {
      validator: function (value) {
        return value > 10
      }
    }
  }
})

二、子组件向父组件通信 

Vue有两个方法是用来处理事件的:

  • 侦听事件使用 $on(eventName)
  • 定义和触发事件使用$emit(eventName)

使用v-on事件进行侦听,(v-on:input=''do'')他侦听到组件内部事件后,

$emit('input'),input这个事件将会传到组件外部乃至上级,从而执行父级实例的do()方法。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值