我想在页面重新加载时检查 localStorage,如果那里已经有一个项目,如果有,我想用当前值(标题和值)更新“cryptocurreny”。
当我使用 addCrypto()
函数添加某些内容时,我的 localStorage 如下所示:
[{"name":"ETH","value":"1.5"},{"name":"BTC","value":"2.75"}]
这是我的组件:
<template>
<div>
<div v-for="coin in cryptocurrency">
<input v-model="coin.name">
<input v-model="coin.value">
</div>
<button @click="addCrypto">
New Cryptocurreny
</button>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
return {
cryptocurrency: [],
}
},
methods: {
set_data() {
localStorage.setItem( 'cryptocurrencies', JSON.stringify(this.cryptocurrency) );
this.cryptocurrency = this.get_data();
},
get_data(){
return localStorage.getItem('cryptocurrencies');
},
addCrypto() {
localStorage.setItem( 'cryptocurrencies', JSON.stringify(this.cryptocurrency) );
this.cryptocurrency.push({ name: '', value: ''});
}
}
}
</script>
但是我尝试在 addCrypto()
函数末尾添加 localStorage.getItem('cryptocurrencies');
但出现错误并在页面重新加载我的cryptocurreny
变量为空。
最佳答案
我无法真正弄清楚你在做什么,但从我看来,set_data()
函数没有在任何地方被调用?
您需要使用已安装或创建的 Hook ( see which one suits you ) 并在那里进行检查。
示例
mounted () {
const saved = localStorage.getItem('cryptocurrencies')
if (saved) {
this.cryptocurrency = saved
}
}
当然,您可以将该代码放入它自己的方法中,并在 mounted()
中调用它。
关于javascript - Vue.js - 刷新时使用当前的 localStorage 更新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48229210/