Vue项目总结(5)-表单组件基础

表单数据处理是一个项目中的必不可少的内容,编写表单组件是完成复杂项目基础。本文深入整理了Vue制作表单组件的各个方面,为后续制作复杂表单组件打好基础。

处理简单数据类型

基本方法

Vue中用prop从父组件向子组件传递数据。

下面是一个简单的输入组件MyInput.vue,定义了属性message,并且通过v-model指令绑定到了html的input上。

<template>
  <div class="my-input">
    <input v-model="message" />
  </div>
</template>
<script>
export default {
  name: 'MyInput',
  props: ['message'],
  watch: {
    message: function() {
      console.log(this.message)
    }
  }
}
</script>

我们在父组件HelloModel.vue中调用这个组件。

<template>
  <div class="hello">
    <my-input :message="message" />
    <div>message: {{ message }}</div>
  </div>
</template>

<script>
import MyInput from './MyInput'

export default {
  name: 'HelloModel',
  components: { MyInput },
  data() {
    return { message: 'hello' }
  }
}
</script>

程序是可以运行的,但是当修改数据时(属性message的值已经发生变化),Vue会发出warn警告。

[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "message"

而且父组件中的message并不会被修改,这是因为Vue的属性是单向绑定。

所有的 prop 都使得其父子 prop 之间形成了一个单向下行绑定:父级 prop 的更新会向下流动到子组件中,但是反过来则不行。

警告的问题很好解决,把prop的赋值给组件的数据,并且将input绑定到这个数据上(这里在input上用v-model只是想说明v-model不能直接用于简单类型的属性)。

<template>
  <div class="my-input">
    <input v-model="innerMessage" />
  </div>
</template>
<script>
export default {
  name: 'MyInput',
  props: ['message'],
  data() {
    return {
      innerMessage: this.message // 用prop赋值
    }
  },
  watch: {
    innerMessage: function() {
      console.log(this.innerMessage)
    }
  }
}
</script>

如何将修改传递回父组件?捕获input事件,发送给父组件,让父组件自己去去修改。

MyInput.vue添加向父组件发送事件的代码。

<template>
  <div class="my-input">
    <input v-model="innerMessage" @input="input" />
  </div>
</template>
<script>
export default {
  name: 'MyInput',
  props: ['message'],
  data() {
    return {
      innerMessage: this.message // 用prop赋值
    }
  },
  watch: {
    message: function() {
      console.log('myinput.message', this.message)
    },
    innerMessage: function() {
      console.log('myinput.innerMessage', this.innerMessage)
    }
  },
  methods: {
    input: function(event) {
      // 接收事件并转发给父组件,注意参数是html的原始对象
      let newVal = event.target.value
      console.log('myinput.input', newVal)
      this.$emit('input', newVal)
    }
  }
}
</script>

HelloModel.vue添加接收子组件事件的代码。

<template>
  <div class="hello">
    <my-input :message="message" @input="input" />
    <div>message: {{ message }}</div>
  </div>
</template>

<script>
import MyInput from './MyInput'

export default {
  name: 'HelloModel',
  components: { MyInput },
  data() {
    return { message: 'hello' }
  },
  methods: {
    input: function(newVal) {
      // 接收子组件传递的事件,注意参数不是event
      this.message = newVal
      console.log('parent.input', this.message)
    }
  }
}
</script>

用v-model简化代码

既然原生的input可以用v-model实现双向绑定,那么MyInput组件是否也可以支持呢?父组件中使用的时候简化为:

<my-input v-model="message" />

其实是可以的,但是MyInput要做改造,生成新的Myinput2.vue文件。

<template>
  <div class="my-input">
    <!-- 注意:这里不是v-model,改成了单向绑定 -->
    <input :value="value" @input="input" />
  </div>
</template>
<script>
export default {
  name: 'MyInput',
  props: ['value'], // 需要指定名称为value的属性
  methods: {
    input: function(event) {
      // 接收事件并转发给父组件,注意参数是原始event对象
      let newVal = event.target.value
      console.log('myinput.input', newVal, event)
      this.$emit('input', newVal)
    }
  }
}
</script>

生成新的HelloModel2.vue文件。

<template>
  <div class="hello">
    <my-input v-model="message" />
    <div>message: {{ message }}</div>
  </div>
</template>

<script>
import MyInput from './MyInput2'

export default {
  name: 'HelloModel',
  components: { MyInput },
  data() {
    return { message: 'hello' }
  }
}
</script>

参考:

.sync修饰符简化

不进行解释了,直接看代码MyInput3.vueHelloModel.vue

<template>
  <div class="my-input">
    <input :value="value" @input="input" />
  </div>
</template>
<script>
export default {
  name: 'MyInput',
  props: ['value'], // 需要指定名称为value的属性
  methods: {
    input: function(event) {
      let newVal = event.target.value
      console.log('myinput.input', newVal)
      // 和.sync修饰符匹配
      this.$emit('update:value', newVal)
    }
  }
}
</script>
<template>
  <div class="hello">
    <!-- 使用.sync修饰符 -->
    <my-input :value.sync="message" />
    <div>message: {{ message }}</div>
  </div>
</template>

<script>
import MyInput from './MyInput3'

export default {
  name: 'HelloModel',
  components: { MyInput },
  data() {
    return { message: 'hello' }
  }
}
</script>

参考:https://cn.vuejs.org/v2/guide/components-custom-events.html#sync-修饰符

补充说明

v-model.sync能简化表单组件的代码,它们有什么区别吗?

v-model写起来更简洁,应为父组件不需要知道表单组件中的属性名(默认使用value)。但是,如果表单组件中有多个input,那么v-model就无法表示绑定关系,因为.sync要指定表单控件的属性名,就可以解决1对多的绑定问题。

使用v-model时还会碰到一个问题,组件上的 v-model 默认会利用名为 value 的 prop 和名为 input 的事件,但是像单选框、复选框等类型的输入控件可能会将 value attribute 用于不同的目的。定义组件时可以用model 选项避免这样的冲突。

{
  model: {  // 定义model
    prop: 'checked',  // 绑定prop传递的值
    event: 'change'  // 定义触发事件名称
  },
  props: {
    checked: Boolean    // 接受父组件传递的值
  }
}

参考:https://cn.vuejs.org/v2/guide/components-custom-events.html#自定义组件的-v-model

处理对象和数组

前面表单控件的属性都是简单类型,如果直接传递对象或数组会有什么不一样?先看看Vue官网文档里的一句话,然后看例子。

注意在 JavaScript 中对象和数组是通过引用传入的,所以对于一个数组或对象类型的 prop 来说,在子组件中改变这个对象或数组本身将会影响到父组件的状态。

传递引用

MyForm.vue实现一个简单的表单组件,输入姓名和年龄。

<template>
  <div class="my-form">
    <div>
      <label>姓名:
        <input v-model="person.name" />
      </label>
    </div>
    <div>
      <label>年龄:
        <input v-model="person.age" />
      </label>
    </div>
  </div>
</template>
<script>
export default {
  name: 'MyForm',
  //model: { prop: 'person' },
  props: { person: Object },
  watch: {
    person: {
      handler: function() {
        console.log('myform.person', this.person)
      },
      deep: true
    }
  }
}
</script>

HelloModel.vue调用表单组件,传递对象。

<template>
  <div class="hello">
    <div>
      <my-form :person="person" />
    </div>
    <div>
      <div>姓名:{{person.name}}</div>
      <div>年龄:{{person.age}}</div>
    </div>
  </div>
</template>

<script>
import MyForm from './MyForm'

export default {
  name: 'HelloModel',
  components: { MyForm },
  data() {
    return { person: { name: 'hello', age: 20 } }
  }
}
</script>

我们在父子组件中都添加了watch,子组件中并没有抛出修改数据事件,当input中的数据发生变化时,父子组件中都可以监控到(父组件在前)。

这里有个问题:是否可以用v-model传递对象呢?我认为是可以的,但是其实没有意义,因为没有抛出修改事件数据就已经被修改了,v-model要解决问题已经不存在了。

不直接修改父组件数据

如果不希望直接修改父组件的数据怎么办?例如:需要对用户输入的数据进行检查,检查通过后再更改父组件的数据。解决办法是在组件中的控件不直接绑定传入的属性对象,而是创建一个组件内的数据进行绑定,检查通过后再将修改合并到父组件的对象中。

子组件MyForm2.vue

<template>
  <div class="my-form">
    <div>
      <label>姓名:
        <input v-model="innerPerson.name" />
      </label>
    </div>
    <div>
      <label>年龄:
        <input v-model="innerPerson.age" />
      </label>
    </div>
  </div>
</template>
<script>
export default {
  name: 'MyForm',
  props: { person: Object },
  data() {
    return {
      // 复制传入的属性
      innerPerson: JSON.parse(JSON.stringify(this.person))
    }
  },
  methods: {
    result() {
      return this.innerPerson
    }
  }
}
</script>

父组件HelloModel5.vue

<template>
  <div class="hello">
    <div>
      <my-form ref="myForm" :person="person" />
    </div>
    <div>
      <div>姓名:{{person.name}}</div>
      <div>年龄:{{person.age}}</div>
    </div>
    <div>
      <button @click="merge">合并数据</button>
    </div>
  </div>
</template>

<script>
import MyForm from './MyForm2'

export default {
  name: 'HelloModel',
  components: { MyForm },
  data() {
    return { person: { name: 'hello', age: 20 } }
  },
  methods: {
    merge() {
      Object.assign(this.person, this.$refs.myForm.result())
    }
  }
}
</script>

渲染函数(render)

当业务逻辑比较复杂时,我们用渲染函数render编写代码可能更有效,所以下面看看如何用render实现上面的这些功能。

简单类型

<script>
export default {
  name: 'MyInput',
  props: ['value'], // 需要指定名称为value的属性
  methods: {
    input: function(event) {
      let newVal = event.target.value
      // 同时支持v-model和sync
      if (this.$listeners.input) this.$emit('input', newVal)
      if (this.$listeners['update:value']) this.$emit('update:value', newVal)
    }
  },
  render(createElement) {
    const vnodeInput = createElement('input', {
      domProps: { value: this.value }, //这里是domProps,不是props
      on: { input: this.input }
    })
    return createElement('div', { class: 'my-input' }, [vnodeInput])
  }
}
</script>

父组件不需要有任何变化,就不贴在这里了。参照之前的代码,就更容易理解render函数,其实它就是将template变成了javascript代码,Vue的build也是这么干的。这里稍微增加了一点逻辑,就是让这个组件同时支持v-modelsync两种方式。

参考:https://cn.vuejs.org/v2/api/#vm-listeners

对象和数组

<script>
export default {
  name: 'MyForm',
  props: { person: Object },
  data() {
    return {
      innerPerson: JSON.parse(JSON.stringify(this.person))
    }
  },
  methods: {
    result() {
      return this.innerPerson
    }
  },
  render(h) {
    const vnodes = [
      ['姓名:', 'name'],
      ['年龄:', 'age']
    ].map(([label, key]) => {
      return h('div', [
        h('label', [
          label,
          h('input', {
            domProps: { value: this.innerPerson[key] },
            on: { input: event => (this.innerPerson[key] = event.target.value) }
          })
        ])
      ])
    })

    return h('div', { class: 'my-form' }, vnodes)
  }
}
</script>

从渲染函数的角度看,处理对象属性并没有什么特殊的地方。这里虽然只有两个属性,但是特意写成了循环的方式,是要示例一下v-forv-ifrender中的写法。

参考:https://cn.vuejs.org/v2/guide/render-function.html#v-if-和-v-for

总结

通过上面的例子把Vue中和表单处理相关的知识点都整理了一遍,解决一般性的问题应该是够用了。但是,表单处理是一个可以无限复杂的事情,会碰到各种各样的情况,细节非常多,还需不断尝试与研究。

本系列其他文章:

Vue项目总结(1)-基本概念+Nodejs+VUE+VSCode

Vue项目总结(2)-前端独立测试+VUE

Vue项目总结(3)-前后端分离导致的跨域问题分析

Vue项目总结(4)-API+token处理流程

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容