render函数
一些场景中需要 JavaScript 的完全编程能力,这时可以用渲染函数,它比模板更接近编译器
render(h) {
return h(tag, {...}, [children])
}
createElement 函数
{ // 与 `v-bind:class` 的 API 相同, // 接受⼀一个字符串串、对象或字符串串和对象组成的数组 'class': { foo: true, bar: false }, // 与 `v-bind:style` 的 API 相同, // 接受⼀一个字符串串、对象,或对象组成的数组 style: { color: 'red', fontSize: '14px' }, // 普通的 HTML 特性 attrs: { id: 'foo' }, // 组件 prop props: { myProp: 'bar' }, // DOM 属性 domProps: { innerHTML: 'baz' }, // 事件监听器器在 `on` 属性内, // 但不不再⽀支持如 `v-on:keyup.enter` 这样的修饰器器。 // 需要在处理理函数中⼿手动检查 keyCode。 on: { click: this.clickHandler } }
插件
// 插件定义 MyPlugin.install = function (Vue, options) { // 1. 添加全局⽅方法或属性 Vue.myGlobalMethod = function () { // 逻辑... } // 2. 添加全局资源 Vue.directive('my-directive', { bind(el, binding, vnode, oldVnode) { // 逻辑... } // ... }) // 3. 注⼊入组件选项 Vue.mixin({ created: function () { // 逻辑... } //... }) // 4. 添加实例例⽅方法 Vue.prototype.$myMethod = function (methodOptions) { // 逻辑... } } // 插件使⽤用 Vue.use(MyPlugin)
例如:移动 $bus 到插件
// plugins/bus.js class Bus { constructor(){} emit(){} on(){} } Bus.install = function(Vue){ Vue.prototype.$bus = new Bus() }
export default Bus // main.js import Bus from './plugins/bus.js' Vue.use(Bus)
组件混入:mixin
混入(mixin)提供了一种分发Vue组件中可复用功能的灵活方式
// 定义⼀一个混⼊入对象 var myMixin = { created: function () { this.hello() }, methods: { hello: function () { console.log('hello from mixin!') } } } // 定义⼀一个使⽤用混⼊入对象的组件 var Component = Vue.extend({ mixins: [myMixin] })
例如:移动dispatch 和 broadcast到mixins
// mixins/emmiter.js // mixin 其实是一个对象 export default { methods: { dispatch(eventName, data) { let parent = this.$parent // 查找父元素 while (parent) { // 父元素用$emit触发 parent.$emit(eventName, data) // 递归查找父元素 parent = parent.$parent } }, boardcast(eventName, data) { boardcast.call(this, eventName, data) } } } function boardcast(eventName, data) { this.$children.forEach(child => { // 子元素触发$emit child.$emit(eventName, data) if (child.$children.length) { // 递归调用,通过call修改this指向child boardcast.call(child, eventName, data) } }) }
上面的混入(mixin),哪个组件想用的话,加入下面的代码就行了
import emmiter from '@/mixin/emmiter.js' // mixins 与 data、props、methods同级 mixins: [emmiter]