父组件数据如何传递给子组件呢?能够经过props属性来实现vue
父组件:函数
<parent> <child :child-msg="msg"></child>//这里必需要用 - 代替驼峰 </parent> data(){ return { msg: [1,2,3] }; }
子组件经过props来接收数据:
方式1:ui
props: ['childMsg']
方式2 :this
props: { childMsg: Array //这样能够指定传入的类型,若是类型不对,会警告 }
方式3:spa
props: { childMsg: { type: Array, default: [0,0,0] //这样能够指定默认的值 } }
这样呢,就实现了父组件向子组件传递数据.code
具体子组件方法blog
<template> <div> 子组件: <span>{{inputName}}</span> </div> </template> <script> export default { // 接受父组件的值 props: { inputName: String, required: true } } </script>
那么,若是子组件想要改变数据呢?这在vue中是不容许的,由于vue只容许单向数据传递,这时候咱们能够经过触发事件来通知父组件改变数据,从而达到改变子组件数据的目的.事件
子组件: <template> <div @click="up"></div> </template> methods: { up() { this.$emit('upup',{
type: id,
brand: itemT.PARENT_ID,
model: itemT.DICTIONARIES_ID
}); //主动触发upup方法,'hehe'为向父组件传递的数据ip
} }
父组件:input
<div> <child @upup="change"></child> //监听子组件触发的upup事件,而后调用change方法 直接在这里打印数据就能够了 </div> methods: { change(date) { this.date = date; } }
若是2个组件不是父子组件那么如何通讯呢?这时能够经过eventHub来实现通讯.
所谓eventHub就是建立一个事件中心,至关于中转站,能够用它来传递事件和接收事件.
let Hub = new Vue(); //建立事件中心
组件1触发:
<div @click="eve"></div> methods: { eve() { Hub.$emit('change','hehe'); //Hub触发事件 } }
组件2接收:
<div></div> created() { Hub.$on('change', () => { //Hub接收事件 this.msg = 'hehe'; }); }
这样就实现了非父子组件之间的通讯了.原理就是把Hub看成一个中转站!
父组件于子组件通讯解决了,可是若是子组件要有操做:
父组件
<!-- model 定义一个 方法事件 close 调用 closeModel 这个函数
定义一个 sure 方法,在此次的组件调用中,执行 gotoCart 函数,执行什么,方法中写,sure方法具体在子组件中哪里调用,就看@click写字组件的哪里。
model组件能够被屡次调用在一个页面的,假如又有一个地方调用了这个组件,此次 确认叫作,查看购物车,那么这里就是要执行跳转了,sure 这个方法不变,仍是定义sure方法,由于
这个方法,在组建中创建了,这里吧sure方法对赢执行的函数,从新一个就行,至关于 sure 方法只是一个 父子组件 的中间商,起到通讯的做用,真正起做用的是这个方法
对应的函数
例如 加入购物车失败
注意:子组件 父组件 绑定对应的函数必须在最外层,子组件的确认按钮执行函数,再确认按钮上,在父组件中没有确认按钮的,父组件只是一个插槽 --> <Model v-bind:mdShow="mdShow" v-on:close="closeModel" v-on:sure="gotoCart"> <span slot="message">加入购物车成功</span> <span slot="leftMessage">取消</span> <span slot="rightMessage">确认</span> </Model>
<!-- 加入购物车失败 -->
<Model v-bind:mdShow="mdShowFail" v-on:close="closeModel" v-on:sure="chenkCart">
<span slot="message">{{messageNew}}</span>
<span slot="leftMessage">取消</span>
<span slot="rightMessage">查看购物车</span>
</Model>
closeModel() {
this.mdShow = false; // 执行要执行的
}
gotoCart(){
}
chenkCart(){
}
子组件
<template> <div class="model_container" v-show="mdShow == true" @click="closeModel"> <div class="model_wrap"> <div class="text"> <slot name="message"></slot> </div> <!-- <p>{{mdShow}}</p> --> <div class="bottom"> <Button class="right_bd" @click="closeModel"> <slot name="leftMessage"></slot> </Button> <Button type="primary" @click="sureModel"> <slot name="rightMessage"></slot> </Button> </div> </div> </div> </template> methods: { closeModel() { // 调用父组件的 close 方法 this.$emit("close"); },
// 调用父组件的 sure 方法
sureModel(){
this.$emit("sure");
}
}
就是性当与是,子组件通知父组件 我操做了,你在父组件该执行你要执行的了