vue组件中的几种传值方式----上篇

vue组件中的传值方式,父子组件,兄弟组件,隔代组件等。看了官网的一些介绍和文档以及一些学习的文章,然后就记下来。方便后面再次学习或者复习。

父组件 => 子组件

属性:props

//child
props:{msg:string}


//parent
<HelloWorld  msg="welcome to your Vue.js App"/>

 

特性:$attrs

//child:并未在props中声明foo,当值传进来时会被归纳到特性中
<p>{{$attrs.foo}}</p>


//parent 
<HelloWorld  foo="foo"/>

  

引用:refs

//parent  
<HelloWorld ref="hw"/>

mounted(){
    this.$refs.hw.xx='xxx'   //本来子组件中的是一个x现在修改三个x
}


//child  

<p>{{xx}}</p>

 data(){
  return{
   xx: 'x'
}
}

子元素:$child  (子元素不保证顺序)  

//parent 
<HelloWorld />
mounted(){
this.$child[0].xx='xxxxx'
}

//child  

<p>{{xx}}</p>

 data(){
  return{
   xx: 'x'
}
}

  

 子组件 => 父组件:自定义事件

//child 
this.$emit('add',good)


//parent 
<Cart @add="cartAdd($event)"><Cart/>

ps:事件谁派发谁监听

  

   兄弟组件:通过共同祖辈组件

通过共同的祖辈组件搭桥,$parent 或 $root.

//brother1
this.$parent .$on('foo',handle)

//brother2
this.$parent.$emit('foo')




例子: (没有去重)
//parent
<HelloWorld />
<HelloWorld />

//child

mounted(){
this.$on('foo',()=>{
  console.log('foo....')
})
this.$emit('foo')

}

  

祖先和后代之间

由于签到层数过多。传递props不切实际,vue提供了provide/inject API完成该任务

provide/inject:能够实现祖先给后代传值(写法类似于props)

//ancestor
provide(){
  return {foo:'foo'}
}

//descendant
inject:['foo']



例子:
//祖先

export default{
provide(){
return{
something:'something'
}
}
}

//后代
export default{
  inject:{ //可以直接注入,(响应式)
msg:'something'
}
}

  先总结了这些,下篇会总结 事件总线 Bus,vuex 和插槽的用法。这些总结都是学习开课吧中课程进行总结的,有兴趣的可以去看一下开课吧的课程。共勉!

猜你喜欢

转载自www.cnblogs.com/yearshar/p/11942386.html
今日推荐