首页 > 其他 > 详细

Vue全家桶开发笔记

时间:2017-02-20 18:30:42      阅读:246      评论:0      收藏:0      [点我收藏+]

1、给v-for遍历产生的元素绑定事件,并动态添加style。
例:

<ul v-for=‘result of results‘>
  <li>
    <div class=‘cut‘>
      <img :src=‘result.src‘>
    </div>
  </li>
</ul>

当图片加载时,记录当前图片原始宽高,处理后传值给style。

首先需求是,在加载图片时记录当前图片原始宽高,所以img标签需要加上@load绑定onload事件。

<ul v-for=‘result of results‘>
  <li>
    <div class=‘cut‘>
      <img @load=‘load‘ :src=‘result.src‘>
    </div>
  </li>
</ul>

<script>
export default {
  data() {
    results: [ 
      { src: ‘src‘, style: null }, 
      { src: ‘src‘, style: null }, 
      { src: ‘src‘, style: null }, 
    ],
  },
  methods: {
    load(e) {
      const img = e.target;
      const [naturalWidth, naturalHeight] = getNatural(img);

      function getNatural(img) {
        let nWidth;
        let nHeight;
        if (img.naturalWidth) {
          nWidth = img.naturalWidth;
          nHeight = img.naturalHeight;
        }
        //省略兼容html 4
        return [nWidth, nHeight];
      }
    },
  },
};
</script>

 

问题来了,这时候load方法虽然获取到了图片的原始宽高,但是传值给style则是个问题。如果要传当前元素的宽高,则需要在模板部分修改:

<img @load=‘load(result)‘ :src=‘result.src‘>

 

这时传的值result会覆盖了event事件。导致load方法出错。

如果需要传event事件需要改成这样:

<img @load=‘load(result, $event)‘ :src=‘result.src‘>

load方法就能同时接受当前遍历对象及触发事件。
ps:methods里面的方法有个默认声明的对象event,里面的属性和$event传过来的一样,但是官方文档没写,不建议使用。

此时在load方法里添加处理style的逻辑:

methods: {
  load(item, e) {
    const img = e.target;
    const [naturalWidth, naturalHeight] = getNatural(img);

    //省略函数
    if (naturalWidth >= narturalHeight) {
      margin = ((naturalWidth * 100) / narturalHeight) / 2;
      item.style = { marginLeft: `-${margin}px`, height: ‘100px‘ };
    } else {
      item.style = { marginLeft: ‘margin-left: -60px‘, height: ‘100px‘ };
    }
  },
},

这里也要注意style是个对象。同时,属性的值不能有分号,否则不会渲染style。

 

Vue全家桶开发笔记

原文:http://www.cnblogs.com/NKnife/p/6420633.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!