我第一次摆弄vue并且让v-bind:style="styleObject"
正常工作时遇到了麻烦。当styleObject中只有一个键/值对时,它可以工作,但当我有多个键/值对时没有任何东西。
运行console.log()
时,值会按原样显示。
我的vue代码:
<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>
答案 0 :(得分:2)
错误在于Vue处理反应的方式。
因为我尝试将键/值对添加到styleObject
,如下所示:
this.styleObject.backgroundPosition = `${image.anchor.x} ${image.anchor.y}`;
由于我试图引用的密钥未事先声明,因此Vue无法检测到更改。解决方案可能是定义所有未来可能是键,这将工作得很好。但是使用vm.$set()
会更好,因为它会处理创建密钥并同时启动反应。简而言之,这一行(和其他人也这样做):
this.styleObject.backgroundPosition = `${image.anchor.x} ${image.anchor.y}`;
成为这个:
this.$set(this.styleObject, 'background-position', `${image.anchor.x} ${image.anchor.y}`);
关于更改原因的Vue文档: https://vuejs.org/v2/guide/reactivity.html