您的位置:首页 > Web前端 > Vue.js

vue实现图片按比例缩放问题操作

2020-08-18 04:09 1851 查看

如下所示:

getImg(src){
var img_url =src
var img = new Image()
img.src=img_url
this.pictureHeight.height = Math.ceil(img.height/img.width * 460)+'px'
},
//首先通过这个方法算出图片的高度/宽度比,460是我设置的宽度,计算得出需要的高度,然后修改容器的高
//度,图片通过height:100%;width:100%撑开,这样图片就不会失真了

vue里面还有一个问题,如果容器只是div的话,修改容器高度,非常简单,如果容器是一个element的插件的话,一般容器的样式都可以通过:style="styleModel"来绑定一个data中的属性styleModel:{height:100px;}这样的方式来修改,

当然如果遇到一些比较复杂的样式调整,也可以通过$refs来修改样式,,但是这样又会出现一个问题,就是$refs定位到的ref属性必须要组件完全加载完成后才能显示出来,所以一般会用this.$nextTick(function(){})的包装起来。

这个方法包装起来后的好处是,会在DOM更新完成后执行这里面的方法,这样就不用担心$refs获取不到的问题了。

this.$nextTick(function(){
// this.$refs.test.$el.childNodes[0].style.height=this.pictureHeight.height
document.getElementsByClassName('el-carousel__container')[0].style.height=this.pictureHeight.height
})

//现在就是通过这两种比较通用的js方式来操作属性了

补充知识:vue实现图片放大的方法

一、v-viewer插件

首先,用命令行安装v-viewer插件:

npm install v-viewer --save

然后,在main.js中注册v-viewer插件,代码如下:

// 实现图片点击放大
import Viewer from 'v-viewer'
import 'viewerjs/dist/viewer.css'
Vue.use(Viewer);
Viewer.setDefaults({
Options: { "inline": true, "button": true, "navbar": true, "title": true, "toolbar": true, "tooltip": true, "movable": true, "zoomable": true, "rotatable": true, "scalable": true, "transition": true, "fullscreen": true, "keyboard": true, "url": "data-source" }
});

注册完成后,就可以在组件中使用v-viewer插件了:

<template>
<!-- imgArr是图片地址的数组,例: ['1.png','2.png'] -->
<viewer :images="imgArr">
<img v-for="src in imgArr" :src="src" :key="src" width="200">
</viewer>
</template>

二、vue-directive-image-previewer插件

用命令行安装vue-directive-image-previewer插件:

npm install vue-directive-image-previewer -D

在main.js中注册:

import VueDirectiveImagePreviewer from 'vue-directive-image-previewer'
import 'vue-directive-image-previewer/dist/assets/style.css'
Vue.use(VueDirectiveImagePreviewer)

在组件中使用vue-directive-image-previewer插件:

<template>
<div>
<img v-image-preview src="123.png"/>
</div>
</template>

以上这篇vue实现图片按比例缩放问题操作就是小编分享给大家的全部内容了,希望能给大家一个参考

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  vue 图片 比例 缩放