render函数详解
一些场景中需要 JavaScript 的完全编程的能力,这时可以⽤用渲染函数,它比模板更接近编译器。
// <div id="box" class="foo"><span>aaa</span></div>
Vue.component("comp", {
// template:'<div id="box" class="foo"><span>aaa</span></div>', (不可行的)
render(h) {
return h('div', { class: { foo: true }, attrs: { id: "box" } }, [
h("span", "aaa")
]);
}
// (jsx语法方式)
// render(h) {
// return <div id="box" class="foo"><span>aaa</span></div>
// }
});
{
// 与 `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
},
}
插件
class Bus {
constructor(){}
emit(){}
on(){}
}
// 使用了install 方法就能使用vue.use()方法
Bus.install = function (Vue) {
Vue.prototype.$bus = new Bus();
}
export default Bus
mixin/ mixin.js
把方法混入到组件中(一般是提取出来的公共的方法等)
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);
}
});
}
使用方法
import emmiter from "@/mixins/emmiter";
<script>
export default {
mixins: [emmiter],
}
</script>