01 - vue中父组件向子组件传值,传的值是ajax请求回来的,存在异步,可能数据还没获取回来就已经实现了传值,在子组件需要渲染 {{数据.属性.属性}} 于是报错
解决方案:传值时加上判定条件,确定数据已经获取了才传值
<template>
<PostdetailArticle
v-if="articleobj.id"
:articledata="articleobj">
</PostdetailArticle>
</template>
<script>
export default {
data: function () {
return {
articleobj: {},
};
},
created: function () {
this.getarticle();
},
methods: {
//获取文章详情
getarticle: function () {
this.$axios({
url: "/posts/" + this.$route.query.id,
}).then((res) => {
this.articleobj = res.data;
});
},
}
};
</script>
02 - element的upload上传文件组件问题
2.1 组件将上传连 ajax 请求也一起封装,无需我们自己处理ajax,相应的,我们的axios的基准路径设置就无效了- 解决方法:平常请求时的 baseURL 需手动拼接。
2.2 API文档要求带上token时,token(token存在localstorage)不能直接在模板用,因为vue实例并没有localstorage - 解决方法:token 先在 data 算好再放进去
<template>
<el-upload
:action="$axios.defaults.baseURL + '/upload'"
:headers="{
Authorization: 'Bearer ' + token,
}"
list-type="picture-card"
:on-success="coverSuccess"
:on-remove="coverRemove"
:file-list="form.cover">
<i class="el-icon-plus"></i>
</el-upload>
</template>
<script>
export default {
data:function(){
return {
token: localStorage.getItem("token"),
}
}
};
</script>
03 - 计算属性有惰性,必须在模板中渲染才会触发
此组件1的页面中有乘机人的信息,乘机人有 几位,需不需要购买保险等,此组件可以用计算属性算出用户的付款金额;但是此页面不需要在模板中渲染数据。
而是要传值给兄弟组件2,在兄弟组件的页面渲染用户的购票信息及付款总金额。
解决方案 - 此组件1在页面渲染计算属性,css - style=“display:none” 实际上渲染了,但是用户看不到而已。再传值给父组件,父组件再传值给兄弟组件2
computed: {
//计算属性,计算总价格,必须渲染才会执行
totalprice: function () {
let total = 0;
const ticketprice =
this.data.seat_infos.org_settle_price * this.users.length;
let insuranceprice = 0;
this.insurances.forEach((item) => {
this.data.insurances.forEach((insurance) => {
if (item == insurance.id) {
insuranceprice += insurance.price * this.users.length;
}
});
});
const tax = this.data.airport_tax_audlet * this.users.length;
total = ticketprice + insuranceprice + tax;
console.log(total);
this.$emit("sendtotal", total, this.users.length); //向父组件传值
return total;
},
},
持续更新中…