vue.js - 将数据存储在本地存储中
问题描述
我有这个组件来创建配方,但我想将数据存储在本地存储中。当我打印“recipeData”时,它会打印在控制台上。例如,我输入配方的名称及其描述等,然后在控制台中打印数据,并打印我输入的元素,但是当我打印“recipeData.title”时,它被打印为没有定义的。而当我想将 recipeData 存储在本地存储中时,它不会存储它。我该如何解决这个问题?
<template>
<v-app>
<v-container>
<v-layout row>
<v-flex xs12 sm6 offset-sm3>
<h2 class="btn-style">Create Recipe</h2>
</v-flex>
</v-layout>
<v-layout row>
<v-flex xs12>
<form @submit.prevent="onCreateRecipe">
<v-layout>
<v-flex xs12 sm6 offset-sm3>
<v-text-field
name="title"
label="Title"
id="title"
v-model="title"
color="#43A047"
required
>
</v-text-field>
</v-flex>
</v-layout>
<v-layout>
<v-flex xs12 sm6 offset-sm3>
<v-text-field
name="imageUrl"
label="ImageUrl"
id="imageUrl"
v-model="imageUrl"
color="#43A047"
required
>
</v-text-field>
</v-flex>
</v-layout>
<v-layout>
<v-flex xs12 sm6 offset-sm3>
<img :src="imageUrl" height="300px" />
</v-flex>
</v-layout>
<v-layout>
<v-flex xs12 sm6 offset-sm3>
<v-text-field
name="description"
label="Description"
id="description"
v-model="description"
color="#43A047"
multi-line
required
>
</v-text-field>
</v-flex>
</v-layout>
<v-layout>
<v-flex xs12 sm6 offset-sm3>
<v-text-field
name="ingredients"
label="Ingredients"
id="ingredients"
v-model="ingredients"
color="#43A047"
multi-line
required
>
</v-text-field>
</v-flex>
</v-layout>
<v-layout row>
<v-flex xs12 sm6 offset-sm3>
<v-btn
class="green darken-1 color"
:disabled="!formIsValid"
type="submit"
>
Create Redcipe
</v-btn>
</v-flex>
</v-layout>
</form>
</v-flex>
</v-layout>
</v-container>
</v-app>
</template>
<script>
export default {
data() {
return {
title: "",
imageUrl: "",
description: "",
ingredients: "",
};
},
computed: {
formIsValid() {
return (
this.title !== "" &&
this.description !== "" &&
this.imageUrl !== "" &&
this.ingredients != ""
);
},
},
methods: {
onCreateRecipe() {
if (!this.formIsValid) {
return;
}
const recipeData = {
title: this.title,
description: this.description,
imageUrl: this.imageUrl,
ingredients: this.ingredients,
};
console.log(recipeData)
console.log("The Local Storage"+localStorage.setItem(this.recipeData));
}
}
};
</script>
<style scoped>
.btn-style {
color: #43a047;
}
.color {
color: #fafafa;
}
</style>
解决方案
要将数据存储到localStorage
,您必须先定义存储名称,然后再定义数据。
localStorage.setItem('storageName', recipeData)
查看 的数据localStorage
。
console.log(localStorage.getItem('StorageName'))
了解更多https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage
并且没有必要this.recipeData
,因为您在函数上声明了变量。获得足够的数据recipeData
推荐阅读
- c# - 将 .bmp 作为 .png 保存到 MemoryStream 时出现 ExternalException
- php - 将自定义变体字段数据添加到 CSV 订单导出 - WooCommerce
- java - 在 Freemarker 中为 Spring Boot 2 提供自定义 TemplateMethodModels
- javascript - Jest 如何将 babel.rc 交给 babel-jest?
- python - 将卷积运算应用于图像 - PyTorch
- mqtt - 2 方式 Secured Mosquitto MQTT 错误
- php - PHP 电子邮件清理过滤器
- node.js - Docker 中的 NodeJS 看不到连接
- c# - 是否有任何属性可以选择 ListView 项目设计时间
- css - 如何在css中用一种颜色绘制半对角线,用另一种颜色绘制另一半对角线