【面试必问】vue组件之间通信的方式

prop 和 $emit

父组件通过props的方式向子组件传递数据,而通过$emit 子组件可以向父组件通信。

<!-- 父组件 father.vue-->
<template>
  <div class="father">
    <son :msg="msg" @changeMsg="changeMsg"></son>
  </div>
</template>
 
<script>
import son from './son.vue'
export default {
  components: { son },
  data() {
    return {
      msg: '我是父组件的msg'
    }
  },
  methods:{
	changeMsg(msg){
		this.msg = msg
  }
}
</script>

<!-- 子组件 son.vue -->
<template>
  <div class="son">
     <p>{{ msg }}</p>
     <button @click="handleClick">修改父组件msg</button>
  </div>
</template>
 
<script>
export default {
  props: {
      msg: String
  },
  methods: {
      handleClick(){
          this.$emit('changMsg', '修改msg')
      }
  }
}

provide 和 inject

多个组件嵌套时,顶层组件provide提供变量,后代组件都可以通过inject来注入变量。这种方式就是vue中依赖注入,该方法用于 祖孙组件之间 的通信。就不用一层一层的传递数据了。

// 祖先组件 提供foo
//第一种
export default {
  name: "father",
  provide() {
    return {
      foo: 'hello'
    }
  },
}
//第二种
export default {
  name: "father",
  provide: {
    foo:'hello~~~~'
  },
}
//后代组件 注入foo, 直接当做this.foo来用
export default {
  inject:['foo'],
}

vuex

路由

slot

ref / $ref

// 父组件 app.vue
 
<template>
  <component-a ref="comA"></component-a>
</template>
<script>
  export default {
    mounted () {
      const comA = this.$refs.comA;
      console.log(comA.name);  // Vue.js
      comA.sayHello();  // hello
    }
  }
</script>
 
// 子组件 A.vue
 
export default {
  data () {
    return {
      name: 'Vue.js'
    }
  },
  methods: {
    sayHello () {
      console.log('hello')
    }
  }
}
 

v-model 和 .sync

v-model 是用来在表单控件或者组件上创建双向绑定的,他的本质是 v-bind 和 v-on 的语法糖,在一个组件上使用 v-model,默认会为组件绑定名为 value 的 prop 和名为 input 的事件。

当我们组件中的某一个 prop 需要实现上面所说的”双向绑定“时,v-model 就能大显身手了。有了它,就不需要自己手动在组件上绑定监听当前实例上的自定义事件,会使代码更简洁。

$parent 和 $children

$attrs和 $listeners

localStorage/sessionStorage

eventBus

$root

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值