vue中组件常用传值方式

.1 父子组件间传值

  • 父组件给子组件传值,直接通过props传值
<custom content="hello world"></custom>
复制代码
  • 子组件给父组件传值,通过 emit发送事件
this.$emit('chooseType', type)
复制代码

父组件接收事件:

<custom content="hello world" @chooseType="handleType"></custom>
复制代码

6.2 非父子组件传值

主要通过事件总线传值

在根节点给 Vue 挂载一个空的 Vue 对象

Vue.prototype.bus = new Vue();

需要发送事件的组件里

this.bus.$emit("change", params)

接收事件的组件

this.bus.$on("change", (msg) => {
    //do yourself work
})

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章