初めてvueを使いこなし、問題が発生してv-bind:style="styleObject"
が正しく動作するようになっています。これは、styleObjectにキー/値ペアが1つしかない場合に機能しますが、複数のキー/値ペアがある場合は何もありません。複数のキーがあるオブジェクトでVueJs 2.xのstylebindが動作しない
console.log()
を実行しているときは、値がそのまま出力されます。
<script>
import Vue from 'vue';
import ImageObject from './SkyCropImage.class';
export default Vue.component('sky-crop', {
props: {
src: String,
focalpoint: String,
mode: String,
round: String,
type: {
type: String,
default: 'img',
},
},
data() {
return {
image: new ImageObject(this.src),
srcString: '',
styleObject: { },
};
},
methods: {
anchorString(image) {
if (this.$el.firstChild.localName !== 'img') {
this.styleObject.backgroundPosition = `${image.anchor.x} ${image.anchor.y}`;
} else {
const pointX = (image.anchor.x.replace('%', '') * 1)/100;
const pointY = (image.anchor.y.replace('%', '') * 1)/100;
const differenceX = image.parent.width - image.calculatedInfo.width;
const differenceY = image.parent.height - image.calculatedInfo.height;
const anchorX = Math.min(0, differenceX * pointX);
const anchorY = Math.min(0, differenceY * pointY);
this.styleObject.transform = `translate(${anchorX}px, ${anchorY}px)`;
}
},
concatSrc(string) {
this.srcString = string;
if (this.type !== 'img') {
this.styleObject.backgroundImage = `url(${string})`;
}
},
},
created() {
this.image.mode = this.mode;
this.image.round = this.round;
this.image.anchor = {
x: this.focalpoint.split(',')[0],
y: this.focalpoint.split(',')[1],
};
},
mounted() {
this.image.setParentInfo(this.$el);
this.image.runCropJob();
this.anchorString(this.image);
this.concatSrc(this.image.outputUrl);
},
});
マイテンプレート:
<div class="skyCrop-parent">
<img
class="skyCrop-element"
alt=""
v-if="type === 'img'"
v-bind:src="srcString"
v-bind:style="styleObject" />
// img result: <img alt="" src="https://source.unsplash.com/Ixp4YhCKZkI/700x394" class="skyCrop-element" style="transform: translate(-50px, 0px);">
<div
class="skyCrop-element"
v-bind:style="styleObject"
v-else>
</div>
//div result: <div class="skyCrop-element"></div>
</div>
コンポーネントが呼び出された方法:
<sky-crop
src="https://source.unsplash.com/Ixp4YhCKZkI/1600x900"
focalpoint="50%,50%"
mode="width"
round="175"
type="div">
</sky-crop>
<sky-crop
src="https://source.unsplash.com/Ixp4YhCKZkI/1600x900"
focalpoint="50%,50%"
mode="width"
round="175">
</sky-crop>