指令

v-model

自定义组件 v-model

前提知识点:自定义组件的 v-modelopen in new window

// src/core/vdom/create-component.js
export function createComponent (
  Ctor: Class<Component> | Function | Object | void,
  data: ?VNodeData,
  context: Component,
  children: ?Array<VNode>,
  tag?: string
): VNode | Array<VNode> | void {
  // ...
  // transform component v-model data into props & events
  // 将 v-model 数据转换为 props&events
  if (isDef(data.model)) {
    transformModel(Ctor.options, data)
  }
  // ...
}

// transform component v-model info (value and callback) into
// prop and event handler respectively.
/**
 * 将 v-model 转换到子组件的 prop、event
 * @param {*} options 组件选项对象
 * @param {*} data 组件数据对象(从模块解析而来的数据 或 调用 createElement 传入的数据对象)
 */
function transformModel (options, data: any) {
  const prop = (options.model && options.model.prop) || 'value'
  const event = (options.model && options.model.event) || 'input'
  ;(data.props || (data.props = {}))[prop] = data.model.value
  const on = data.on || (data.on = {})
  if (isDef(on[event])) {
    on[event] = [data.model.callback].concat(on[event])
  } else {
    on[event] = data.model.callback
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35

组件上的v-model默认会利用名为valueprop和名为input的事件,但是当组件选项对象里传递了model属性,则会使用model属性的propevent

在模板编译阶段,会将v-model绑定的值传给data.model.value,并添加data.model.callback用于改变data.model.value的值。

待补充内容