Vue.js父子组件通信-自定义事件
组件props用法:
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
}
}
}
自定义事件学习:
父组件通过属性将数据传递给子组件
子组件通过$on监听子组件事件,通过$emit来触发父组件的事件。
子组件代码:
<template>
<div id="child">
<p>子组件显示父组件输入:{{message}}</p>
<button v-on:click="childMethod">子组件按钮 add</button>
</div>
</template>
<script>
export default {
props:{
message: {
type: String,
default: "hello child"
}
},
data() {
return {
count:0
}
},
methods:{
childMethod:function() {
this.count += 1
// 当父组件事件触发之后,子组件通知父组件触发某一个事件。
this.$emit("fatherEmit")
}
},
components:{
}
}
</script>
<style>
</style>
父组件代码:
<template>
<div id="father">
<p>父组件的计数器{{fatherCount}}</p>
父组件的输入:<input v-model="message">
<!--父组件通过属性绑定给子组件传值-->
<child v-bind:message = "message" v-on:fatherEmit = "fatherAdd"></child>
</div>
</template>
<script>
import Child from "../comment/Child"
export default{
data() {
return {
fatherCount:0,
message:"hello"
}
},
methods:{
fatherAdd:function() {
this.fatherCount += 1;
}
},
components:{
Child:Child
}
}
</script>
<style>
</style>