以下例子中 com-two是子组件 。
一、父---->子
1、数据传递 ,msg是父组件的数据
父组件中写
<com-two :title="msg"></com-two>
子组件中在vue中写
props:['title']
子组件使用时写
<span>{{title}}</span>
2、方法的传递,show是父组件的方法
父组件中写
<com-two :met="show"></com-two>
子组件在vue中写
props:['met']
子组件使用时写
<button @click="met">点我使用父组件show方法</button>
二、子--->父
1、数据的传递,msg是子组件数据(子组件中需要以某种方式例如点击事件的方法来触发一个自定义事件,将需要传的值作为$emit的第二个参数,该值将作为实参传给响应自定义事件的方法,在父组件中注册子组件并在子组件标签上绑定对自定义事件的监听)
子组件在vue中写
sendFn(){
this.$emit('fuFn',this.msg)
}}
子组件在模板中写
<button @click="sendFn">点击向父组件发送数据</button>
父组件在vue中写
methods:{
onfn(val){
alert(val) / /val即为msg
}}
父组件在模板中写
<com-two @fuFn="onfn"></com-two>
三、父组件直接获取子组件数据(主动获取)
父组件中写
<com-two ref="child"></com-two>
取
this.$refs.child.msg
四、父组件直接调用子组件方法(show是子组件方法)
父组件中写
<com-two ref="child"></com-two>
调用
this.$refs.child.show
五、子组件直接获取父组件数据或方法
子组件中写
this.$parent.数据
this.$parent.方法
六、利用插槽
1、父组件给子组件传数据 (msg是父组件的数据)
父组件中写
<com-two>{{this.msg}}</com-two>
子组件模板中写
<slot>这是默认数据</slot>
2、多插槽
父组件中写
<com-two>
<div slot="s1">this.msg1</div>
<div slot="s2">this.msg2</div>
<div slot="s2">this.msg2</div>
</com-two>
子组件中写
<slot name="s1">this.msg1</slot>
<slot name="s2">this.msg2</slot>
<slot name="s2">this.msg2</slot>
3、作用域插槽
子组件给父组件传数据 arr是子组件数据
父组件中写
<com-two>
<template slot-scope="scores">
<ul>
<li v-for="v in scores.arr">{{v.name}}</li>
</ul>
</template>
</com-two>
子组件
<slot :arr="arr">这是默认数据</slot>
七、非父子级关系传递数据(例为在脚手架中怎样使用)
1、需要准备一个公共的js文件,实例对象,用来传递数据。
在assets目录下新建一个common.js里面写
import Vue from 'vue';
var Event=new Vue();
export default Event;
2、在发数据和取数据的两个组件中都要引入该js文件
import Event from './../assets/common'
3、发送数据
Event.$emit('名字',值)
4、接收数据(val就传过来的值)
Event.$on('名字',function(val){})
网友评论