我在封装头像组件时遇到了以下问题:
1.getSrc 必须放在 computed 里放在 methods 不生效
2.getStyle 必须放在 methods 里放在computed 不生效(指的是当设置width为10rem时,它还是算默认值6rem)
调用 <base-avatar wdith="10rem"></base-avatar>
<template>
<div id="avatar" :style="getStyle" :class="getClass">
<img :src="getSrc" @error="handlerError" />
</div>
</template>
<script>
// 默认头像
import defaultImg from "@agent/assets/img/default-avatar.jpg";
// 加载失败
import errorImg from "@agent/assets/img/error-img.jpg";
export default {
name: "BaseAvatar",
data() {
return {
isError: false
};
},
props: {
// 图片路径
src: {
type: String
},
// 头像形状
shape: {
type: String,
default: "circle",
validator: function(value) {
return ["normal", "circle", "rectangle"].indexOf(value) !== -1;
}
},
width: {
type: String,
default: "6rem"
},
height: {
type: String,
default: "6rem"
}
},
methods: {
handlerError() {
this.isError = true;
},
getStyle() {
let styleList = [];
styleList.push({ width: this.width });
styleList.push({ height: this.height });
return styleList;
}
},
computed: {
getClass() {
let classList = [];
if (this.shape == "normal") {
classList.push("normal");
}
if (this.shape == "circle") {
classList.push("circle");
}
if (this.shape == "rectangle") {
classList.push("rectangle");
}
return classList;
},
getSrc() {
if (!this.isError) {
// 正常
if (this.src) {
return this.src;
} else {
return defaultImg;
}
} else {
// 图片加载失败
return errorImg;
}
}
}
};
</script>
<style lang="scss" scoped>
// 形状
.normal {
border-radius: 5px;
}
.rectangle {
border-radius: 0px;
}
.circle {
border-radius: 50%;
}
#avatar {
overflow: hidden;
position: relative;
& > img {
width: 100%;
height: 100%;
}
}
</style>
你的调用都写错了。。。
wdith
->width
绑定都应该用计算属性。
组件是一个对象,对象有若干个属性(property)和若干方法(method)。方法即为一个函数(function)挂在对象上,需要通过对象来调用,例如对象中通过
this.fun()
或对象外instanceFoo.fun()
。访问每个属性实际上在内部是执行一个函数的结果,即
getter
的调用。例如this.a
是调用了属性a
的getter
。计算属性就是让我们去自定义某个属性的
getter
(原生 JavaScript 也有计算属性)。计算属性首先识别当前属性有没有被谁调用,有就执行,没有就不执行。进一步还会去识别自定义的getter
中有依赖了谁,依赖改变也要执行(保证最终结果准确)。在 Vue 中以
:propName="propFoo"
的写法来将当前组件对象的属性,如果属性是一个计算属性,则将这个计算属性上的函数执行并返回结果传入子组件。