【问题标题】:How to make "two-way binding" Vue如何制作“双向绑定”Vue
【发布时间】:2021-11-01 20:44:17
【问题描述】:

我有子组件,它的功能是上传照片。上传的照片分配给名为“照片”的子组件数据。 我需要将名为“file”的父数据与名为“photo”的子数据绑定。当“照片”改变时,“文件”也应该改变。

子组件:

<template>
  <div class="select">
    <img v-if="previewFile" :src="previewFile" alt="" />
    <img v-else src="/images/empty.jpg" alt="" />
    <label class="btn" for="image-upload">{{ btnLabel }}</label>
    <input id="image-upload" type="file" ref="file" @change="uploadFile" />
  </div>
</template>

import { mapGetters } from "vuex";

export default {
  name: "SelectPhoto",

  data() {
    return {
      file: null,
      previewFile: null,
    };
  },
  
  methods: {
    uploadFile() {
      this.file = this.$refs.file.files[0];
    }
  }
}

父组件:

<template>
    <SelectPhoto :btn-label="text.RU.photoSelect.choosePhoto" v-model:file.sync="file"/>
    <BaseButton :label="text.RU.photoSelect.knowName" @do="$emit('getResult', file, previewFile)" />
</template>

<script>
export default {
  data() {
    return {
      file: null,
    };
  },
};
</script>

【问题讨论】:

    标签: javascript vue.js data-binding components vue-component


    【解决方案1】:

    您已经在BaseButton 组件上使用了$emit。您也可以将其用于this.file。在你的子组件中是这样的:

    uploadFile() {
        this.file = this.$refs.file.files[0];
        this.$emit('sendMyFile', this.file)
    }
    

    在你的父组件中,对动作做出反应:

        <SelectPhoto @sendMyFile="getMyFile" :btn-label="text.RU.photoSelect.choosePhoto" v-model:file.sync="file"/>
    

    同样在父组件中使用the.file

    methods: {
        getMyFile(file) {
          // do something
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2020-06-11
      • 2017-04-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-10
      • 2021-11-04
      • 2016-04-14
      • 1970-01-01
      • 2017-11-11
      相关资源
      最近更新 更多