vue开发干货

vue组件传值

2019-02-13  本文已影响45人  ALililili__

父组件向子组件传值

props

①父组件内设置要传的数据『data(){ id: value}』

②在父组件中引用的子组件上绑定一个自定义属性并把数据绑定在自定义属性上『< myBtn :atrid='id'></ mybtn>』

③在子组件添加参数props:['atrid'],即可

父组件调用子组件方法

ref

①父组件<child ref="mychild"></child>

            this.$refs.mychild.parentHandleclick( )

子组件向父组件传值

$emit

①由于父组件需要参数,所以在父组件中的标签上定义自定义事件,在事件内部获取参数;『@myEvent=" callback"在callback函数中接收参数』

②在子组件中触发自定义事件,并传参。『this.$ emit('父组件中的自定义事件',参数)』

.sync 修饰符  (子组件改变父组件数据)

①父组件 <comp :foo.sync="bar"></comp>

②子组件 this.$emit('update:foo', newValue)

子组件调用父组件方法

$parent

子组件的方法中 this.$parent.fatherMethod();

子组件里用$emit向父组件触发一个事件,父组件监听这个事件

父组件  <child @fatherMethod="fatherMethod"></child>

子组件的方法中  this.$emit('fatherMethod');

父组件把方法传入子组件中,在子组件里直接调用这个方法

父组件<child :fatherMethod="fatherMethod"></child>

子组件方法中

if (this.fatherMethod) {

         this.fatherMethod();

       }

组件之间传值

bus

上一篇 下一篇

猜你喜欢

热点阅读