如何在渲染函数中实现“v-model”?

时间:2018-04-13 06:41:19

标签: vue.js

当我阅读渲染函数数据时:https://vuejs.org/v2/guide/render-function.html#The-Data-Object-In-Depth

没有v-model个地方,Vue.js 2.0中不存在v-model

以下是官方网站给出的数据示例,但它没有说明v-model展示位置:

{
  // Same API as `v-bind:class`
  class: {
    foo: true,
    bar: false
  },
  // Same API as `v-bind:style`
  style: {
    color: 'red',
    fontSize: '14px'
  },
  // Normal HTML attributes
  attrs: {
    id: 'foo'
  },
  // Component props
  props: {
    myProp: 'bar'
  },
  // DOM properties
  domProps: {
    innerHTML: 'baz'
  },
  // Event handlers are nested under `on`, though
  // modifiers such as in `v-on:keyup.enter` are not
  // supported. You'll have to manually check the
  // keyCode in the handler instead.
  on: {
    click: this.clickHandler
  },
  // For components only. Allows you to listen to
  // native events, rather than events emitted from
  // the component using `vm.$emit`.
  nativeOn: {
    click: this.nativeClickHandler
  },
  // Custom directives. Note that the `binding`'s
  // `oldValue` cannot be set, as Vue keeps track
  // of it for you.
  directives: [
    {
      name: 'my-custom-directive',
      value: '2',
      expression: '1 + 1',
      arg: 'foo',
      modifiers: {
        bar: true
      }
    }
  ],
  // Scoped slots in the form of
  // { name: props => VNode | Array<VNode> }
  scopedSlots: {
    default: props => createElement('span', props.text)
  },
  // The name of the slot, if this component is the
  // child of another component
  slot: 'name-of-slot',
  // Other special top-level properties
  key: 'myKey',
  ref: 'myRef'
}

您看到有许多关键字,例如refkeyprops等等,我怎样才能实现这一要求?

2 个答案:

答案 0 :(得分:1)

props: {
    myProp: 'bar',
    value: 'someValue'
  },
  on: {
    click: this.clickHandler,
    input: function(value) {
        // change someValue here using value
    },

  },

答案 1 :(得分:0)

仅针对使用渲染功能的有状态组件:https://vuejs.org/v2/guide/render-function.html#v-model

如果您要使用具有渲染功能的功能组件:

export default Vue.extend({
  name: 'Input',
  functional: true,
  props: {
    value: {
      type: String as PropType<string>,
      default: '',
    }
  },
  render(createElement, { data, props, slots, listeners }) {
    const input = createElement('input', {
      domProps: {
        value: props.value,
      },
      on: {
        input: (e: { target: HTMLInputElement }) => {
          const onItemChange = listeners['item-change'] as (
            value: string
          ) => void
          if (onItemChange) onItemChange(e.target.value)
        })
      }
    })
  })
})

然后使用此组件:

<Input :value="yourValue" @item-change="setYourValue" />