Vue.js组件间通信


更多关于Vue.js的系列文章请点击Vue.js开发实践(0)-目录页


一、props选项

1.1、基础使用

prop 是父组件用来传递数据的一个自定义属性。

父组件的数据需要通过 props 把数据传给子组件,子组件需要显式地用 props 选项声明 “prop”:


<div id="app">
    <child message="hello!"></child>
</div>
 
<script>
// 注册
Vue.component('child', {
  // 声明 props
  props: ['message'],
  // 同样也可以在 vm 实例中像 "this.message" 这样使用
  template: '<span>{{ message }}</span>'
})
// 创建根实例
new Vue({
  el: '#app'
})
</script>

1.2、组件动态通信

组件间可以通过v-bind指令进行动态的数据交互:


<div id="app">
    <div>
      <input v-model="parentMsg">
      <br>
      <child v-bind:message="parentMsg"></child>
    </div>
</div>
 
<script>
// 注册
Vue.component('child', {
  // 声明 props
  props: ['message'],
  // 同样也可以在 vm 实例中像 "this.message" 这样使用
  template: '<span>{{ message }}</span>'
})
// 创建根实例
new Vue({
  el: '#app',
  data: {
    parentMsg: '父组件内容'
  }
})
</script>

二、自定义事件

2.1、使用v-on和this.$emit()接受和发送数据

父组件可以通过prop属性和子组件通信,但是子组件不能使用prop属性和父组件通信,所以我们需要通过自定义事件去让子组件和父组件通信。

<div id="vue5">
		<h1>子组件向父组件通信</h1>
		<Child v-on:sign="fatherRecevice($event)"></Child>
</div>
var Child = {
	//子组件模板中有一个点击触发事件,以此来将消息发送给父组件
	template: '<button v-on:click="sendMessageToFather">发送数据给父组件{{message}}</button>',
			data(){
				return{
					message: 'ABC'
				}
			},
			methods: {
				sendMessageToFather(){
					//调用this.$emit方法唤醒v-on:sign标识的父组件方法fatherRecevice($event),第二个参数为传递的数据
					this.$emit('sign',this.message);
				}
			}
}

new Vue({
	el: '#vue5',
	components: {
		Child
	},
	methods: {
		//这是父组件方法,用于接受数据
		fatherRecevice(message){
			alert("接受到数据"+message);
		}
	}
})

效果:
在这里插入图片描述在这里插入图片描述

三、prop参数校验

vue为prop参数提供了一套校验的基本数据类型:

  • String
  • Number
  • Boolean
  • Function
  • Object
  • Array
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
      }
    }
  }
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

BoringError

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

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

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

打赏作者

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

抵扣说明:

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

余额充值