v-model 和子组件? [英] v-model and child components?

查看:42
本文介绍了v-model 和子组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单并使用 v-model 绑定一个输入:

现在我想提取输入并使其成为自己的组件,那么如何将子组件的值绑定到父对象form.name?

解决方案

如文档中所述

v-model 是语法糖:

<块引用>

<输入v-bind:value=某物"v-on:input=something = $event.target.value">

为自定义组件实现 v-model 指令:

  • 为组件指定一个 value 属性
  • 使用计算设置器为内部值创建计算属性(因为你不应该在组件内修改 prop 的值)
  • 为计算属性定义一个 get 方法,该方法返回 value 道具的值
  • 为计算属性定义一个 set 方法,该方法在属性更改时发出带有更新值的 input 事件

这是一个简单的例子:

Vue.component('my-input', {模板:`<div>我的输入:<input v-model="inputVal">

`,道具:['价值'],计算:{输入值:{得到() {返回 this.value;},设置(val){this.$emit('input', val);}}}})新的 Vue({el: '#app',数据() {返回 {foo: '酒吧'}}})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js"></script><div id="应用程序"><!-- 使用 v-model... --><my-input v-model="foo"></my-input><!-- 和这个一样...--><my-input :value="foo" @input="foo = $event"></my-input>{{ foo }}

感谢 @kthornbloom 发现之前实现的问题.

Vue 3 中的重大变化

根据文档,对Vue 3 中的 v-model 实现:

  • ->modelValue
  • 输入 ->update:modelValue

I have a form and bind an input using v-model:

<input type="text" name="name" v-model="form.name">

Now I want to extract the input and make it it's own component, how do you then bind the values of the child component to the parents object form.name?

解决方案

As stated in the documentation,

v-model is syntactic sugar for:

<input
 v-bind:value="something"
 v-on:input="something = $event.target.value">

To implement the v-model directive for a custom component:

  • specify a value prop for the component
  • make a computed property with a computed setter for the inner value (since you should not modify the value of a prop from within a component)
  • define a get method for the computed property which returns the value prop's value
  • define a set method for the computed property which emits an input event with the updated value whenever the property changes

Here's a simple example:

Vue.component('my-input', {
  template: `
    <div>
      My Input:
      <input v-model="inputVal">
    </div>
  `,
  props: ['value'],
  computed: {
    inputVal: {
      get() {
        return this.value;
      },
      set(val) {
        this.$emit('input', val);
      }
    }
  }
})

new Vue({
  el: '#app',
  data() {
    return { 
      foo: 'bar' 
    }
  }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.3/vue.min.js"></script>
<div id="app">
  <!-- using v-model... -->
  <my-input v-model="foo"></my-input>
  
  <!-- is the same as this... -->  
  <my-input :value="foo" @input="foo = $event"></my-input>

  {{ foo }}
</div>

Thanks to @kthornbloom for spotting an issue with the previous implementation.

Breaking changes in Vue 3

Per the documentation, there are breaking changes to the v-model implementation in Vue 3:

  • value -> modelValue
  • input -> update:modelValue

这篇关于v-model 和子组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆