使用vue开发输入型组件更好的一种解决方式(子组件向父组件传值,基于2.2.0)

(本人想封装一个带有input输入框的组件)

之前使用vue开发组件的时候,在遇到子组件向父组件传递值时我采用的方法是这样的: 

比如子组件是一个输入框,父组件调用时需要获取到子组件输入的值,子组件通过watch监听输入框的值然后通过this.$emit给父组件,再在父组件v-on绑定相应方法获取到从子组件传入的值,再将传入的值给对应的data:

childInput.vue:
<template>
   <input type="text" v-model="inputValue"> </template> <script> export default{ data() { return{inputValue: null} }, watch:{ inputValue(val){ this.$emit('getValue', val) } } } </script> parent.vue: <template> <div> <child-input v-on:getValue="(val)=>{someValue = val}"/> </div> </template> <script> export default{ data(){ someValue: null } } </script>

这样的解决方式感觉有点蠢,因为这样写每次我调用子组件的时候都会需要写一个v-on:getValue然后将相应的值赋给对应的data数据,比如在写嵌套组件的时候,一般一个Input组件包含多个input类型,然后在form表单调用的时候可能会调用10个以上的input子组件,就意味着需要些10多个的v-on:xxx=”(val)=>{yyy = val}”。

然而今天在浏览官网时发现了另外一个解决方法:

相对于上述的老办法倒是方便了许多,不过这种方法只有在vue 2.2.0以上才可以使用(根据官网的说法):

parent.vue:
<template>
   <div>
      <child-input v-model="someValue"/> </div> </template> <script> export default{ data(){ someValue: null } } </script> childInput.vue: <template> <span> <input ref="input" v-bind:value="value" v-on:input="updateValue($event.target.value)" > </span> </template> <script> export default{ data() { return { inputValue: null,//输入框的值 } }, methods: { updateValue(val) { this.$emit('input', val) } } } </script>

这样写每次调用子组件只用像一般的元素写v-model双向绑定数据即可。

猜你喜欢

转载自www.cnblogs.com/huancheng/p/9633670.html