# vue-study **Repository Path**: ldlw/vue-study ## Basic Information - **Project Name**: vue-study - **Description**: 记录平时学习vue练习代码 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: lesson1 - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2021-02-18 - **Last Updated**: 2021-11-02 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # 笔记 ### vue常用组件通信 * props * $emit/$on * event bus * vuex ### 边界情况 * $parent * $children * $root * $refs * provide/inject * 非props属性 * $attrs * $listeners ### event 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))) } } } ``` * vue中如何使用 ``` // main.js Vue.prototype.$bus = new Vue() // child1 this.$bus.$on('foo',hanlde) // child2 this.$bus.$emit'foo') ``` ### $parent/$root > 兄弟组件之间通信可通过共同祖辈搭桥 ``` // brother1 this.$parent.$on('foo',handle) // brother2 this.$parent.$emit('foo') ``` ### $children > 父组件可以通过$children访问子组件实现父子通信 ``` //parent this.$children[0].xx = xxx ``` ### refs 获取子节点引用,也可以元素dom属性 ``` this.$ref.aa.xx = 'xxx'; ``` ### $attrs/$listeners > 不在props属性中声明 ``` // parent // child

{{$attrs.foo}}

``` ``` > $attrs隔代组件通信,在最外层组件传递,子组件属性展开 // index.vue,msg从爷爷辈传递过去的数据 Parent有child组件,原封不动传给孙子组件,bind将以键值对展开 // $listeners隔代事件转发,把事件展开传给子组件 // index.vue methods:{ onFoo() { console.log('爷爷组件的方法') } } child组件可以 this.$emit('foo') inheritAttrs: false 关闭根标签显示 ``` provide/inject 跨很多层,不是响应式的,但可以传响应式的过来 ``` // index.vue export default() { provide() { return { bar:'bar' // 引用类型的对象可以变 } } } // child.vue

{{bar}}

export default() { //inject:['bar'], // 注入,类似于props //inject: {bar1:'bar'} // 起别名 inject: { bar2: { from:'bar', default:'111' // 默认值 } } } ``` 插槽 内容分发api,用于复合组件开发 ``` 1、匿名插槽 // comp1
//hello放入
// parent hello 2、具名插槽 将内容放到子组件指定位置 // comp2
// parent // 默认使用default做参数 // 具名插槽用插槽做参数 3、作用域插槽 分发内容要用的子组件中的数据 // comp3
//最终替换还是它
// parent // 把v-slot的值指定为作用域上下文对象 ``` github.com/57code/vue-study 使用Vue.extend实现create方法 ``` const comp = {data:{},props:{}} const Ctor = Vue.extend(comp) new Ctor({propsData:{}}) ```