【问题标题】:vuejs2 slots how to communicate with parentvuejs2 插槽如何与父级通信
【发布时间】:2021-07-11 13:55:20
【问题描述】:

我想创建一个 formRow 组件,它有一个用于输入字段的插槽和 vee-validate 用于验证

这是我的标记

//form
<vFormRow validate="required" v-slot="{ onInput, errors }">
  <vTextfield @input="onInput" :errors="errors"/>
</vFormRow>

我尝试将值发送给父级并在插槽上使用@input="onInput" 获取值,但这不起作用

//formrow
<template>
  <div class="mb-4">
    <v-validation-provider
      v-slot="{ errors }"
      :rules="validate"
    >
      <label>{{ label }}</label>
      <slot 
        :onInput="onInput"
        :errors="errors"
      />
      <vFormError
        :message="errors[0]"
      />
    </v-validation-provider>
  </div>
</template>

<script>
import { ValidationProvider as vValidationProvider } from 'vee-validate'
import vRadioButton from '@primitives/textfield'
import vFormError from '@primitives/formError'
export default {
  components: {
    vTextfield,
    vFormError,
    vValidationProvider
  },
  props: {
    value: {
      type: String,
      default: '',
    },
    validate: {
      type: String,
      required: true,
    }
  },
  methods: {
    onInput(value) {
      console.log(value)
    }
  }
}
</script>
//textfield

<template>
  <div>
    <input :value="value" @input="onInput"/>
  </div>
</template>
<script>
export default {
  props: {
    value: {
      type: String,
      default: '',
    },
    errors: {
      type: Array,
      default: () => {}
    }
  },
  data: {
    return {
      // local_value: ''
    }
  }
  methods: {
    onInput(e) {
      // this.local_value = e.target.value
      this.$emit('input', e.target.value)
    }
  }
}
</script>

我做错了什么?

【问题讨论】:

    标签: vue.js slot


    【解决方案1】:

    您实际上并没有将插槽道具传递给&lt;vTextfield&gt;。我想您可能会假设 &lt;slot&gt; 上的数据绑定和事件处理程序会自动应用于插槽的子级,但事实并非如此。

    要使用value 插槽属性,从v-slot 解构它,并将其绑定到&lt;vTextfield&gt; 子:

    <vFormRow validate="required" v-slot="{ value }">
      <vTextfield :value="value" />
    </vFormRow>
    

    您也可以将onInput 方法作为插槽属性传递:

    // vFormRow.vue
    <slot :onInput="onInput" />
    

    然后将事件处理程序绑定到&lt;vTextfield&gt;

    <vFormRow validate="required" v-slot="{ onInput }">
      <vTextfield @input="onInput" />
    </vFormRow>
    

    【讨论】:

      猜你喜欢
      • 2015-05-20
      • 2013-02-02
      • 1970-01-01
      • 1970-01-01
      • 2017-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-18
      相关资源
      最近更新 更多