1、父组件向子组件传值
<!-- haha在vue实例的data中定义并设置默认值 -->
<my-component :myData='haha'></my-component>
2、子组件接受父组件传的值
通过props
来接受, 如下:
props: ['myData']
3、父组件向子组件传方法
<!-- aaFunc在vue实例的methods中 -->
<!-- 不带参数 -->
<my-component :myFunc='aaFunc'></my-component>
<!-- 带参数 -->
<my-component :myFunc='aaFunc(args)'></my-component>
4、子组件调用父组件的方法
子组件中通过$emit
来调用父组件的方法,
// 不带参数
this.$emit('myFunc')
// 带参数
this.$emit('myFunc', '22')
5、父组件调用子组件的方法或属性
通过在父组件上设置ref
属性,来为组件定义一个名字,然后使用$refs
来获取该父组件并调用它里面的方法和属性,如下:
<!-- aaFunc在vue实例的methods中 -->
<!-- 使用组件时,用ref定义组件的名字 -->
<my-component ref='myComponent'></my-component>
在父组件文件中调用子组件的方法和属性:
// 调用myComponent组件的aaFunc方法
this.$refs.myComponent.aaFunc()
// 调用myComponent组件的hh属性
this.$refs.myComponent.hh
6、子组件中更新属性时同步到父组件中
可以使用.sync
修饰符(详情可见vue修饰符总结及积累一节),如下:
<!-- haha在vue实例的data中定义并设置默认值 -->
<my-component :myData.sync='haha'></my-component>
子组件文件中:
// 接收
props: ['myData']
// 修改myData并同步更新到父组件
this.$emit('update:myData', '22')