vue指令实现源码
以下是 Vue 指令实现的源码解析,主要分为核心实现逻辑和常见指令示例:
Vue 指令核心实现
Vue 的指令系统通过 directives 模块实现,核心代码位于 src/core/vdom/modules/directives.js。关键实现逻辑如下:
// 指令钩子函数
export default {
create: updateDirectives,
update: updateDirectives,
destroy: function unbindDirectives(vnode) {
updateDirectives(vnode, emptyNode)
}
}
function updateDirectives(oldVnode, vnode) {
if (oldVnode.data.directives || vnode.data.directives) {
_update(oldVnode, vnode)
}
}
指令注册机制
指令通过 Vue.directive() 全局注册或组件选项的 directives 局部注册:
// 全局注册
Vue.directive('focus', {
inserted: function (el) {
el.focus()
}
})
// 局部注册
new Vue({
directives: {
focus: {
inserted: function (el) {
el.focus()
}
}
}
})
常见内置指令实现
v-model
双向绑定实现原理(以 input 为例):
function model(el, dir, _warn) {
const value = dir.value
const modifiers = dir.modifiers
const tag = el.tag
if (tag === 'input') {
el.addEventListener('input', () => {
context[value] = el.value
})
}
}
v-show
通过 CSS display 属性控制:
function show(el, value) {
el.style.display = value ? '' : 'none'
}
v-if/v-else
通过注释节点和条件渲染实现:
function processIfConditions(el, parent) {
const prev = findPrevElement(parent.children)
if (prev && prev.if) {
addIfCondition(prev, {
exp: el.elseif,
block: el
})
}
}
自定义指令生命周期
指令包含以下生命周期钩子:
bind(el, binding, vnode) {
// 只调用一次,指令第一次绑定到元素时调用
}
inserted(el, binding, vnode) {
// 被绑定元素插入父节点时调用
}
update(el, binding, vnode, oldVnode) {
// 所在组件的 VNode 更新时调用
}
componentUpdated(el, binding, vnode, oldVnode) {
// 所在组件及子组件全部更新后调用
}
unbind(el, binding, vnode) {
// 只调用一次,指令与元素解绑时调用
}
指令参数解析
binding 对象包含以下属性:
{
name: '指令名(不带v-前缀)',
value: '指令的绑定值',
oldValue: '指令绑定的前一个值',
expression: '字符串形式的指令表达式',
arg: '传给指令的参数',
modifiers: '包含修饰符的对象'
}
以上内容展示了 Vue 指令系统的核心实现机制,包括注册方式、生命周期管理以及常见内置指令的实现原理。







