Vue:如何通过包装器组件将值绑定到输入?

我知道您可以使用v-model将值绑定到同一组件中的输入。如何为输入创建包装器组件并将其绑定值?

Login.vue

<template>
  <div id="Login">
    <Input v-bind:value="email"/>    
    <Input v-bind:value="password"/>

  </div>
</template>
<script>
  import Input from './Input.vue'
  import Button from './Button'

  export default {
    name: 'Login',components: {
        Input,Button,},data: () => ({
        email:'test',password:'test',}),methods: {
        login: () => { debugger; },//this.email and this.password are still set to test
    }
  }
</script>

Input.vue

<template>
  <div class="input>
   <input v-model="value"/>
  </div>
</template>
<script>
  export default {
    name: 'Input',props: {
        value: String,}
</script>

当前设置结果

[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: "value"

通过发出事件来做到这一点的唯一方法吗?

HOPEHAPPY111 回答:Vue:如何通过包装器组件将值绑定到输入?

如果我正确理解,则可以尝试创建透明包装器(在我的情况下为AppInput)

SomeParent.vue

<div>
  <AppInput v-model="parentModel" />
</div>

AppInput.vue

<template>
  <input
    class="app-input"
    v-bind="$attrs"
    :value="value"
    v-on="{
      ...$listeners,input: event => $emit('input',event.target.value)
    }">
</template>
<script>
export default {
  name: "AppInput",inheritAttrs: false,props: ["value"]
};
</script>

one of articles

,

最好的方法是使用v-model进行包装,使用on / emit进行输入

<div id="Login">
    <Input v-model="email"/>    
    <Input v-model="password"/>    
</div>

...

<div class="input>       
   <input        
     v-bind:value="value"
     v-on:input="$emit('input',$event.target.value)"
   >
</div>
,

这样做可以直接在v-model组件中实现input

<template>
  <div class="input>
   <input :value="value" @input="$emit('input',$event.target.value)"/>
  </div>
</template>
<script>
  export default {
    name: 'Input',props: ["value"]
  }
</script>

然后像这样在父组件中使用它:

<template>
  <div id="Login">
    <Input v-model="email"/>    
    <Input v-model="password"/>
  </div>
</template>
<script>
  import Input from './Input.vue'
  import Button from './Button'

  export default {
    name: 'Login',components: {
        Input,Button,},data: () => ({
        email:'test',password:'test',}),methods: {
        login: () => { debugger; },//this.email and this.password are still set to test
    }
  }
</script>

See here

本文链接:https://www.f2er.com/3165393.html

大家都在问