VueJS: background img загружается во всех одноуровневых компонентах, а не в компонент, через который было загружено изображение - PullRequest
0 голосов
/ 03 июля 2019

В этой демонстрации codeSandBox дочерний cmp содержит входной файл изображения,

Файл загружается и читается с использованием reader.readAsDataURL(file) в качестве фонового изображения родительского элемента оболочки div..

Проблема в том, что загруженный файл повторяется у всех братьев и сестер.

Я хочу, чтобы загруженный файл затрагивал только компонент, в который был загружен дочерний элемент.

Parent.vue

<template>
  <div id="app">
    <div v-for="n in 5">
      <div class="wrapper" :style="bgImg">
        <child @imageSelected="updateBgImg($event)"/>
      </div>
    </div>
  </div>
</template>

<script>
  import child from "./components/child";

  export default {
    name: "App",
    data() {
      return {
        bgImgURL: "Image URL",
        bgImg: {}
      };
    },
    methods: {
      updateBg(url) {
        this.bgImgURL = url;
        this.bgImg = {
          "background-image": "url(" + this.bgImgURL + ")"
        }
      }
    },
    components: {
      child
    }
  }
</script>

child.vue

<template>
  <div>
    <input type="file" @change="getImage">
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  props: {
    msg: String
  },
  methods: {
    getImage(e) {
      var file = e.target.files[0];
      this.createImage(file);
    },
    createImage(file) {
      var reader = new FileReader();
      reader.readAsDataURL(file);

      var vm = this;
      reader.onload = function() {
        vm.$emit("imageSelected", this.result);
      };
    }
  }
};
</script>

Спасибо

1 Ответ

0 голосов
/ 03 июля 2019

Обновите изображение у вашего ребенка.Пример для кодов andbox

Ваш родитель выглядит так

<template>
  <div id="app">
    <div v-for="n in 5" :key='n'>
        <child/>

        <!-- <child @imageSelected="updateBg($event)"/> -->
    </div>
  </div>
</template>

<script>
import child from "./components/child";

export default {
  name: "App",
  data() {
    return {
      msg: "Parent Message",
      // testUrl: "Image URL",
      // bgImg: {}
    };
  },
  methods: {
    // updateBg(url,index) {
    //   // this.testUrl = url;
    //   this.bgImg[index] = {
    //     "background-image": "url(" + url + ")"
    //   };
    //   // console.log(this.bgImg);
    // },

  },
  components: {
    child
  }
};
</script>

<style>
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
.wrapper {
  width: 300px;
  height: 100px;
  margin-bottom: 30px;
  border: 1px solid red;
  background-size: cover;
}
</style>

и ваш ребеноккак это

<template>
  <div>
    <div class="wrapper" :style="img">
      <input type="file" @change="getImage">
    </div>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  props: {
    msg: String
  },
  data(){
    return {
      img:''
    }
  },
  methods: {
    getImage(e) {
      var file = e.target.files[0];
      this.createImage(file);
    },
    createImage(file) {
      var reader = new FileReader();
      reader.readAsDataURL(file);

      var vm = this;
      reader.onload = function() {
        // console.log(this.result)
        vm.img = {
        "background-image": "url(" + this.result + ")"
      }
        // don't need
        // vm.$emit("imageSelected", this.result);
      };
    }
  }
};
</script>

Обновлено

Обновление изображения в родительском от дочернего.Пример на коде ручки

Ваш родитель

<template>
  <div id="app">
    <div v-for="n in imgCount" :key="n">
      <div class="wrapper" :style="imgs[n]">
        <sibling/>
        <child :image-id="n" @imageSelected="updateBg($event)"/>
      </div>
    </div>
  </div>
</template>

<script>
import child from "./components/child";
import sibling from "./components/simpleCmp";

export default {
  name: "App",
  data() {
    return {
      imgCount: 5,
      msg: "Parent Message",
      testUrl: "Image URL",
      bgImg: {},
      imgs: []
    };
  },
  methods: {
    updateBg(item) {
      // console.log(item.index);
      this.$set(this.imgs, item.index, item.bg)
    }
  },
  components: {
    child,
    sibling
  }
};
</script>

Ваш ребенок

<template>
  <div>
    <input type="file" @change="getImage">
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  props: {
    msg: String,
    imageId: Number
  },
  methods: {
    getImage(e) {
      var file = e.target.files[0];
      if (!file) return;
      this.createImage(file);
    },
    createImage(file) {
      var reader = new FileReader();
      reader.readAsDataURL(file);

      var vm = this;
      reader.onload = function() {
        // console.log(this.result);
        vm.$emit("imageSelected", {
          index: vm.imageId,
          bg: {
            "background-image": "url(" + this.result + ")"
          }
        });
      };
    }
  }
};
</script>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...