避免直接改变道具(渲染功能)

时间:2020-07-27 07:24:15

标签: vuejs2 vue-render-function

只是尝试使用render函数创建组件,但是我得到了一个奇怪的警告:

enter image description here

以下组件:

import Vue, { CreateElement, VNode } from 'vue'

export default Vue.extend({
  name: 'p-form-input',
  props: {
    type: String,
    name: String,
    value: {
      type: [ String, Number ]
    },
    placeholder: String,
    disabled: Boolean
  },
  data() {
    return {
      localValue: ''
    }
  },
  watch: {
    value(value) {
      this.localValue = value
    }
  },
  mounted() {
    this.localValue = this.$props.value
  },
  methods: {
    onInput(e: any) {
      this.localValue = e.target.value
      this.$emit('input', this.localValue)
    },
    onChange(e: any) {
      this.localValue = e.target.value
      this.$emit('change', this.localValue)
    }
  },
  render(h: CreateElement): VNode {
    return h('input', {
      class: 'form-control',
      domProps: {
        disabled: this.$props.disabled,
        type: this.$props.type,
        name: this.$props.name,
        placeholder: this.$props.placeholder,
        value: this.localValue
      },
      on: {
        input: this.onInput,
        change: this.onChange
      }
    })
  }
})

组件上的v-model="inputValue"确实触发了inputValue上的输入/更改,但是我收到警告了吗?

使用vue 2.6.11!

编辑:

不要介意ts忽略,它会抱怨找不到它的类型,这样更美观!

<template>
  <div id="app">
    <p-form-input type="text" name="some_input" v-model="inputValue" /> {{ inputValue }}
  </div>
</template>

<script lang="ts">
import Vue from 'vue'
// @ts-ignore
import PFormInput from 'vue-components/esm/components/form-input'

export default Vue.extend({
  name: 'App',
  components: {
    PFormInput,
  },
  data() {
    return {
      inputValue: 'fdsdsfdsf'
    }
  }
});
</script>

1 个答案:

答案 0 :(得分:1)

您有一个名为“ value”的道具,然后在方法中使用了一个名为“ value”的变量:

    onInput(e: any) {
      const value = e.target.value

      this.localValue = value

      this.$emit('input', value)
    },

请勿重用名称“值”。实际上,您甚至不需要该变量:

    onInput(e: any) {
      this.localValue = e.target.value
      this.$emit('input', this.localValue)
    },

与onChange相同:

    onChange(e: any) {
      this.localValue = e.target.value
      this.$emit('change', this.localValue)
    }