在vue中,有时候我们需要缓存一个页面,这个时候会用到keep-Alive。
触发场景:
在引用同一个子组件得两个页面,且该子组件会使用到dom元素得时候。
例如子组件
<template>
<div class="yd-dialog-black-mask" v-show="showMask">
<div class="layer-wraper">
<div class="picture">
<img src="../../../static/img/photo.png" alt>
</div>
<div class="content">
<h1>{{staffNo}}</h1>
<canvas id="qrcode"></canvas>
<span class="desc">扫我就是我的人~</span>
</div>
<div class="btn-wraper">
<div class="close-icon" @click.stop="close()"></div>
</div>
</div>
</div>
</template>
<script>
import QRCode from "qrcode";
import { mapState } from "vuex";
export default {
props: {
showMask: Boolean
},
data() {
return {
staffNo: ""
};
},
computed: {
...mapState({
quickMark: state => state.user.quickMark
})
},
methods: {
close() {
this.$emit("on-close");
}
},
created() {
this.staffNo = localStorage.getItem("staffNo");
},
mounted() {
let self = this;
this.$nextTick(() => {
QRCode.toCanvas(
document.querySelector("#qrcode"),
this.quickMark,
function(err) {
if (err) {
self.toast("生成二维码异常,请稍后再试");
}
}
);
});
}
};
</script>
<style lang="less" scoped>
.yd-dialog-black-mask {
top: 0 !important;
bottom: 0 !important;
justify-content: center !important;
align-items: center;
.layer-wraper {
position: relative;
.picture {
position: absolute;
text-align: center;
width: 100%;
.p2r(top, -120);
img {
.p2r(width, 312);
}
}
.content {
text-align: center;
box-sizing: border-box;
.p2r(padding-top, 120);
.p2r(width, 530);
.p2r(height, 618);
border-radius: 10px;
background: #fff;
h1 {
.p2r(font-size, 36);
.p2r(line-height, 40);
font-weight: bold;
}
#qrcode {
.p2r(margin-top, 14);
.p2r(width, 350) !important;
.p2r(height, 350) !important;
}
.desc {
display: block;
.p2r(margin-top, 16);
.p2r(font-size, 30);
}
}
.btn-wraper {
.close-icon {
.p2r(width, 70);
.p2r(height, 70);
margin: auto;
.p2r(margin-top, 44);
background: url("../../img/icon-close.png") no-repeat center center;
background-size: 100%;
}
}
}
}
</style>
解决方法如上所示就是用nextTick来解决。。不使用nextTick来解决。。不使用nextTick来解决。。不使用nextTick得时候在从keep-Alive得组件切换到另一个组件时,dom元素未被销魂,导致子组件document.querySelector("#qrcode"),选中得时keep-alive得组件而非新得路由组件得dom。导致新路由页面得二维码未生成。