组件化是vue的核心思想,它能提升开发效率,方便重复使用,简化调试步骤,提高整个项目的可维护 性,便于多人协同开发
+1)属性propsvue
// child props: { msg: String } // parent <HelloWorld msg="Welcome to Your Vue.js App"/>
+2) 特性$attrsnode
// child:并未在props中声明foo <p>{{$attrs.foo}}</p> // parent <HelloWorld foo="foo"/>
+3)引用refsvuex
// parent <HelloWorld ref="hw"/> mounted() { this.$refs.hw.xx = 'xxx' }
+4)子元素$children(子元素不保证顺序)vue-cli
// parent this.$children[0].xx = 'xxx'
// child this.$emit('add', good) // parent <Cart @add="cartAdd($event)"></Cart>
经过共同的祖辈组件搭桥,$parent或$root。ide
// brother1 this.$parent.$on('foo', handle) // brother2 this.$parent.$emit('foo')
因为嵌套层数过多,传递props不切实际,vue提供了 provide/inject API完成该任务
1.provide/inject:可以实现祖先给后代传值组件化
// ancestor provide() { return {foo: 'foo'} } // descendant inject: ['foo']
+.事件总线:建立一个Bus类负责事件派发、监听和回调管理this
// Bus:事件派发、监听和回调管理 class Bus{ constructor(){ this.callbacks = {} } $on(name, fn){ this.callbacks[name] = this.callbacks[name] || []
实践中能够用Vue代替Bus,由于它已经实现了相应功能 vuex:建立惟一的全局数据管理者store,经过它管理数据并通知组件状态变动prototype
范例:组件通讯 组件通讯范例代码请参考components/communicate 插槽 插槽语法是Vue 实现的内容分发 API,用于复合组件开发。该技术在通用组件库开发中有大量应用。 匿名插槽 具名插槽 将内容分发到子组件指定位置 // comp1 <div> <slot></slot> </div> // parent <comp>hello</comp> 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) // child2 this.$bus.$emit('foo')
+.实践中能够用Vue代替Bus,由于它已经实现了相应功能
+.vuex:建立惟一的全局数据管理者store,经过它管理数据并通知组件状态变动调试
组件通讯范例代码请参考components/communicatecode
插槽语法是Vue 实现的内容分发 API,用于复合组件开发。该技术在通用组件库开发中有大量应用。
1.匿名插槽
// comp1 <div> <slot></slot> </div> // parent <comp>hello</comp>
2.具名插槽
将内容分发到子组件指定位置 // comp2 <div> <slot></slot> <slot name="content"></slot> </div> // parent <Comp2> <!-- 默认插槽用default作参数 --> <template v-slot:default>具名插槽</template> <!-- 具名插槽用插槽名作参数 --> <template v-slot:content>内容...</template> </Comp2>
3.做用域插槽
分发内容要用到子组件中的数据 // comp3 <div> <slot :foo="foo"></slot> </div> // parent <Comp3> <!-- 把v-slot的值指定为做用域上下文对象 --> <template v-slot:default="slotProps"> 来自子组件数据:{{slotProps.foo}} </template> </Comp3>
4.范例插槽相关范例请参考components/slots中代码