如果想在一个组件中调用另一个组件,在子组件中使用父组件数据和方法,在父组件中使用子组件数据,该如何做呢,现在我们就通过程序来学习父子组件之间的通讯

https://cn.vuejs.org/v2/guide/components-props.html
0.bugs
1.
模板要一个根元素.这是重要的

这种alert的传参是错误的

一.父子组件
1.vm相当于一个根组件,里面的components就相当于它的子组件

2.同理.我们可以在一个全局组件注册它的子组件
2.1创建组件
2.2注册组件
2.3使用组件



二.子组件使用父组件数据
1.父组件在调用子组件的时候传递数据
:别名="父数据名称"
2.在子组件中注册父组件传递过来的数据
props:['别名1', ... ]
3.在子组件中使用父组件传递过来的数据
{{别名}}

这里看到子组件中没有数据

我们从父组件传递数据

我们在子组件中使用父组件传递过来的数据
三.子组件使用父组件方法
1.父组件传递方法名称给子组件(记住如果加圆括号就变成调用)
2.在子组件中定义方法,在方法中触发父组件传递过来的方法
this.$emit("父组件传递的方法名称")
3.在子组件中调用父组件传递的方发
@click="方法名称"



四.父组件使用子组件数据

简单的说,就是父组件调用子组件,子组件从父组件获取的方法中,嵌入了自己的数据
1.定义父组件方法传递参数
2.将子组件的数据传递给从父组件获取的方法
this.$emit("父组件传递的方法","子组件传递的数据")
3.在父组件的方法中使用该数据


网友评论