vue 组件通信

1.定义

组件化系统提供一种抽象,独立可复用并构建复制大型应用系统,所有应用都可以抽象成一个抽象树。

  • 优点:提高开发效率,可重复使用,易维护调试,便于多人协同。

2.通信方式

2.1父子/子父传值

//props
props: { msg: String } //子页面
<HelloWorld msg="Welcome to Your Vue.js App"/>//父页面

//子父传值 @xx=  $emit
this.$emit('add', info)  //子页面

<HelloWorld @add="addInfo"/>//父页面
methods: {
    addInfo(info){
        ...
    }
}

复制代码

2.2跨组件事件总线 Bus (其实就是订阅发布模式)


//跨组件事件总线 Bus (其实就是订阅发布模式)
class Bus {
    constructor() {
        this.callbacks = {}
    }
    $on(name, fn) {
        this.callbacks[name] = this.callbacks[name] || []
        this.callbacks[name].push(fn)
    }
    $emit(name, args) {
        if (this.callbacks[name]) {
            this.callbacks[name].forEach(cb => cb(args))
        }
    }
}
// main.js
Vue.prototype.$bus = new Bus()
// child1
this.$bus.$on('foo', handle)//监听
methods: {
    handle(info){
        ...
    }
}
// child2
this.$bus.$emit('foo') //派发

Vue 类也实现了Bus的逻辑,所以直接new一个vue实现总线
复制代码

2.3跨组件vuex,全局对象状态管理

创建唯⼀的全局数据管理者store,通过它管理数据并通知组件状态变更。

//src/store/user.js
export default {
  state: { isLogin: false },
  mutations: {
   login(state) {
      state.isLogin = true;
   },
  },
}
//引入
//src/store/index.js
Vue.use(Vuex)
export default new Vuex.Store({
  modules: {
    user
  },
})
//main.js
import store from './store'
new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')
  
//login.vue调用
<template>
  <button @click="login" v-if="!$store.state.isLogin">登录</button> 
</template>

this.$store.commit('login')  
复制代码

2.4兄弟组件parentparent或root

//通过同一个父亲的bus达到数据传输
// brother1
this.$parent.$on('foo', handle)
// brother2
this.$parent.$emit('foo')
复制代码

2.4$children ⽗⼦通信

//直接访问
this.$children[0].xx = 'xxx' //$children不能保证⼦元素顺序
//$children与$ref区别, $children可以直接访问,$ref需要提前指定在 标签上指定
复制代码

2.5$attrs/$listeners

包含了⽗作⽤域中不作为 prop 被识别 (且获取) 的特性绑定 ( class 和 style 除外)。当⼀个组件没有
声明任何 prop 时,这⾥会包含所有⽗作⽤域的绑定 ( class 和 style 除外),并且可以通过 vbind=”$attrs” 传⼊内部组件——在创建⾼级别的组件时⾮常有⽤。

// child:并未在props中声明foo
<p>{{$attrs.foo}}</p>
// parent
<HelloWorld foo="foo"/>
复制代码
© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享