vue computed localStorage All In One
vue computed localStorage All In One
cache bug
-
methods ✅
-
computed ❌
-
props ✅
<template>
<div class="parent">
<Child :msg="name" />
<button @click="updateName">change localStorage name</button>
</div>
</template>
<script>
import Child from './Child.vue'
/* eslint-disable no-unused-vars */
// ... your code here with unused vars...
/* eslint-enable no-unused-vars */
export default {
name: 'Parent',
components: {
Child,
},
props: {
msg: String,
},
data() {
return {
id: 1,
name: 'eric',
};
},
computed: {},
// beforeCreate() {
// window.localStorage.removeItem('name');
// },
mounted() {
window.localStorage.setItem('name', this.name);
// setTimeout(() => {
// this.name = 'xgqfrms';
// window.localStorage.setItem('name', this.name);
// }, 3000);
},
unmounted() {
window.localStorage.removeItem('name');
},
// destroyed() {
// window.localStorage.removeItem('name');
// },
methods: {
updateName() {
window.localStorage.setItem('name', 'xgqfrms' + Date.now());
this.name = 'xgqfrms' + Date.now();
window.localStorage.setItem('name', this.name);
},
},
}
</script>
<style scoped>
</style>
<template>
<div class="child">
<h1>{{msg}}</h1>
<div>❌ name = {{name}}</div>
<div>❌ localName = {{localName}}</div>
<div>❌ funcLocalName = {{funcLocalName}}</div>
<div>✅ mannulName = {{mannulName()}}</div>
<!-- <div v-if="domReady">❌ window.localStorage.getItem('name') = {{window?.localStorage?.getItem('name')}}</div> -->
<!-- Child.vue?b541:6 Uncaught (in promise) TypeError: Cannot read property 'localStorage' of undefined -->
<!-- <div>❌ window.localStorage.getItem('name') = {{window?.localStorage?.getItem('name')}}</div> -->
</div>
</template>
<script>
const getLocalName = () => {
return window.localStorage.getItem('name');
}
export default {
name: 'Child',
props: {
// msg: String,
msg: {
type: String,
default: '',
required: true,
},
},
data() {
return {
domReady: false,
name: window.localStorage.getItem('name'),
};
},
computed: {
funcLocalName() {
console.log('getLocalName =', getLocalName());
return getLocalName();
},
localName() {
console.log('localName =', window.localStorage.getItem('name'));
return window.localStorage.getItem('name');
},
},
mounted() {
this.domReady = true;
},
unmounted() {
this.domReady = false;
},
methods: {
mannulName() {
console.log('mannulName =', window.localStorage.getItem('name'));
return window.localStorage.getItem('name');
},
},
}
</script>
<style scoped>
</style>
refs
©xgqfrms 2012-2020
www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!
原创文章,版权所有©️xgqfrms, 禁止转载 🈲️,侵权必究⚠️!
本文首发于博客园,作者:xgqfrms,原文链接:https://www.cnblogs.com/xgqfrms/p/14489235.html
未经授权禁止转载,违者必究!