【问题标题】:Vue js for loop - trigger js when new element added into domVue js for loop - 当新元素添加到dom时触发js
【发布时间】:2021-07-23 18:36:51
【问题描述】:

我想使用这个库实例化多个 图像裁剪器https://fengyuanchen.github.io/cropper.js/

我迭代比率并将 4 个图像添加到 DOM 中(我有 4 个比率 - 所以每个比率一个图像):

<li v-for="ratio in ratios" :key="ratio.id">
    <div>
        <img v-bind:src="uploadRec.url" />
    </div>
</li> 

我需要为每一张图片做这样的事情:

const image = document.getElementById('image');
const cropper = new Cropper(image, {
  aspectRatio: 16 / 9,
  crop(event) {
    console.log(event.detail.x);
    console.log(event.detail.y);
    console.log(event.detail.width);
    console.log(event.detail.height);
    console.log(event.detail.rotate);
    console.log(event.detail.scaleX);
    console.log(event.detail.scaleY);
  },
});

我无法理解它 - 当新元素被 vue 添加到 dom 时,我如何触发一些 javascript?

【问题讨论】:

  • “当新元素被 vue 添加到 dom 时”部分在哪里?
  • @ikiK 在 v-for 循环中?
  • 看看this组件是怎么做的
  • @LawrenceCherone 所以我必须使用组件来做类似的事情?还是喜欢 v-pre 并跳过 vuejs?
  • 我要求您向我们展示 vue app js 代码,而不是您如何将组件添加到 html 中。即时消息询问您如何以及何时添加数据。看看这个:vuejs.org/v2/guide/instance.html 在生命周期图下。可能有助于在中间的某个地方做你想做的事..

标签: vue.js vuejs3


【解决方案1】:

您可以引入 Image 组件,或将 template ref 绑定到每个 img 元素,并在将 ref 添加到 dom 时利用 watchEffect 执行裁剪器逻辑。

<template>
  <li v-for="ratio in ratios" :key="ratio.id">
    <div>
        <img :ref="el => {if (el) { imgs[ratio.id] = el; }}"/>
    </div>
</li> 
</template>

<script>
  import {ref, reactive, watchEffect} from "vue";

  export default {
    name: "App",

    setup() {
            
        const ratios = ref([
        {id: 1}, {id: 2}, {id: 3}
      ]);
      
      const imgs = ref({});
      
      watchEffect(() => {
        for (let id in imgs.value) {
          const el = imgs.value[id];
          
        }
      });
      
      return {ratios, imgs};
    }
}
</script>

当然,如果您的比率状态没有改变,您也可以依赖onMounted 挂钩。这样您就不再需要watchEffect

【讨论】:

    猜你喜欢
    • 2012-07-25
    • 1970-01-01
    • 2010-10-27
    • 1970-01-01
    • 1970-01-01
    • 2012-05-31
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多