先是第一种方式(这种方式不安全,可以对其进行修改)
第一步:在public下新建config文件夹,然后里面建一个js文件,在这个文件里向window上自定义挂载属性
public/config/test.js
window.abcd = {
name:'window自定义属性名',
key:'1',
hhh:'啦啦啦'
}
第二步:在public下的index.html上中加载上面的js文件即可在全局拿到window中自定义的属性
public/index.html
<script src="/config/test.js"></script>
home.vue
mounted() {
console.log(window.abcd,'window上自定义的属性----->>')
console.log(window,'window属性')
},
第二种就是向window上添加的属性不可被修改(通过 Object.defineProperties)
咱们只需要修改上面的第一步就可以了,如下:向window上挂载setSubSystemData、getSubSystemData两个方法
/**
* 向window上挂载setSubSystemData、getSubSystemData方法
* 不可修改
*/
Object.defineProperties(window, {
setSubSystemData: {
get() {
return function(key, value) {
localStorage.setItem(key, value)
}
},
set(val) {
console.log(val,'触发了set')
}
},
getSubSystemData: {
get() {
return function(key) {
return localStorage.getItem(key)
}
},
set(val) {
console.log(val,'触发了set')
}
}
})
Object.defineProperties 这个方法可以戳一下下方链接
Object.definePropertieshttps://blog.csdn.net/m0_51431448/article/details/122619525