
1 <script> 2 export default { 3 props: ["lists"], 4 data() { 5 return { 6 isactive: false, 7 actveName: "", 8 selContent: "請選擇" 9 }; 10 }, 11 mounted() { 12 console.log("我被創建了"); 13 this.$nextTick(function() { 14 document.addEventListener("click",this.outClick); 15 }); 16 }, 17 beforeDestroy(){ 18 console.log("我被銷毀了"); 19 document.removeEventListener("click",this.outClick); 20 }, 21 methods: { 22 isShowSel() { 23 this.isactive = !this.isactive; 24 }, 25 light(name) { 26 this.actveName = name; 27 this.selContent = this.actveName; 28 this.$emit("selectVal", this.actveName); 29 }, 30 outClick(e) { 31 if (this.$refs.mySelBox&&!this.$refs.mySelBox.contains(e.target)) { 32 this.isactive = false; 33 } 34 } 35 } 36 }; 37 </script>
Vue封裝下拉框組件時,為實現點擊下拉框之外的部分收起下拉框,因此為document綁定原生事件addEventlistener("click“,fun);
問題發現:
在切換頁面之后(當前下拉組件會被自動銷毀),但綁定的事件還未被摧毀。
vue文檔說明:
document
的監聽事件確切來說是獨立於vue
項目之外的,如果你不銷毀會一直存在。
參考:
https://segmentfault.com/q/1010000016613680
ttps://segmentfault.com/q/1010000016141322/a-1020000016609969