vue.js 如何将两个不同的数据从子组件传递到父组件的v-model中?

dkqlctbz  于 2023-06-24  发布在  Vue.js
关注(0)|答案(1)|浏览(130)

我正在一个项目中使用vuejs 2和typescript。我想在父组件中传递两个不同的数据。dataattachments使用vue-property-decorator。当我已经在父组件v-model中使用数据时,我不知道如何引用attachments?你知道做这件事的正确方法吗?

父组件

<template>
  <ChildComponent 
  v-model="data" 
  :attachments="attachments" How to refer attachments ?
  />
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator'
import ChildComponent from '~/components/ChildComponent'

@Component({
  components: {
    ChildComponent
  }
})
export default class ParentComponent extends Vue {
  data: any = {};
  attachments: any = [];
}
</script>

子组件

<template>
  <form>
    <input type="text" v-model="data.firstname" />
    <input type="text" v-model="data.lastname" />
    <input type="file" multiple v-model="attachments" />
  </form>
</template>

<script lang="ts">
import { Component, VModel, Vue } from 'vue-property-decorator'

@Component
export default class ChildComponent extends Vue {
  @VModel() data!: any;
  @VModel() attachments!: any;
}
</script>

感谢您的支持和帮助。

yxyvkwin

yxyvkwin1#

这在Vue 3 SFC中对我有效,抱歉没有TS -应该很容易转换。
支持ChatGpt。
具有v模型的父对象:

<template>
  <ChildComponent v-model="parentData" />
  <p>Parent Data: {{ parentData }}</p>
</template>

<script setup>
import ChildComponent from './ChildComponent.vue';
import { ref } from 'vue';

const parentData = ref('');

</script>

孩子有一个观察者和发射(不是我最喜欢的):

<template>
  <input v-model="modelValue" />
</template>

<script setup>
import { ref, watch, emit } from 'vue';

props: {
  modelValue: {
    type: Object,
    required: true
  }
},

const childData = ref('');

// Update the childData with the prop value
childData.value = props.modelValue;

// Watch for changes in childData and emit them to the parent component
watch(childData, (newValue) => {
  emit('update:modelValue', newValue);
});
</script>

我可能还可以优化得更多,但今天就到此为止吧。
带有'update:x'的emit语法对我来说是新的,因为我希望只是将所有对象绑定在一起,但没有运气。
希望有人能提供一个更好的解决方案。

相关问题