如果用户导航到不同的屏幕或注销会话,则输入的表单数据不应消失



这里我正在尝试,而用户在表单输入字段中输入数据。假设我有一个类别字段,我在该字段中输入了一个类别,在标题字段中也输入了标题,依此类推。我已经在输入字段中输入了一个值,如果用户导航到任何其他页面,或者如果用户从会话注销并再次用户登录,则输入字段中的输入数据或值不应消失,如果用户浏览到其他屏幕或用户注销会话,则该值应保持原样。我们如何在vue.js中实现这一点我正在尝试,但失败了。我想实现如果用户导航到其他屏幕或注销会话,它不应该消失或刷新输入的数据,数据应该是原样


<div>
<h1>Post Ad</h1>
<p>
<input type="text" v-model.lazy="category" placeholder="Search your category"
name="category" maxlength="200" id="id_post_type">
</p>
<p>
<input placeholder="Title" type="text" v-model="title" name="title" maxlength="60">
</p>
<p>
<input type="text" placeholder="Address" v-model="address" name="address">
<input type="text" placeholder="City" v-model="city" name="city" maxlength="100">
</p>
<p>
<input type="text" placeholder="State" v-model="state" name="state">
<input type="text" placeholder="Zip" v-model="zip" name="zip" maxlength="50">
</p>
<p>
<input  type="number" placeholder="Price" v-model="price" name="price" step="any">
</p>
<p>
<textarea name="description" v-model="description" placeholder="Ad description.."></textarea>
</p>
<button style="background-color:lightgray"id="buttonDemo" style="outline:none;" class="step1_next" @click.prevent="next()" >Next</button>
</div>

vue.js

<script>
new Vue({
el: '#q-vikreya',
data() {
return {
step:1,
category:'',
title:'',
address:'',
city:'',
state:'',
zip:'',
price:'',
description:'',
methods: {
submitForm: function(){
axios({
method : "POST",
url: "{% url 'PostAd' %}", //django path name
headers: {'X-CSRFTOKEN': '{{ csrf_token }}', 'Content-Type': 'application/json'},
data : {"category":this.category, "title":this.title,
"address":this.address,
"city": this.city,
"state": this.state,
"zip": this.zip,
"price": this.price,
"description": this.description,
"radio_price": this.radio_price,
"Job_title": this.model,
},//data
}).then(response => {
console.log("response");
console.log(response.data);
this.success_msg = response.data['msg'];
window.location.replace('{% url "classifieds" %}')  // Replace home by the name of your home view
}).catch(err => {
this.err_msg = err.response.data['err'];
console.log("response1");
console.log(err.response.data);
});
},
},
})
</script>

我认为您要做的是,当用户没有提交表单,并且离开了您希望它重新加载数据的页面时。为此,您可以使用本地存储。如果您希望它从服务器加载数据,那么您需要调用服务器并取回数据,然后使用mounted生命周期挂钩加载数据。

您想要做的是在使用beforeDestroy生命周期钩子销毁Vue实例之前,将其挂接到Vue实例中。然后,您需要将数据保存到localStorage。首先,您需要获取所有要保存的数据或整个数据对象(通过使用this.$data(,并将其转换为JSON,因为localStorage无法接受复杂的数据类型。然后你会把它提交给localStorage,就像这样:

beforeDestroy(){
localStorage.formSave = JSON.stringify(this.$data);
}

下次,当用户打开页面时,您希望从localStorage获取所有数据,并将其加载回对象。我们需要使用JSON.parse()将其从字符串转换为对象。为此,我们将使用一个循环,这样我们就可以确保如果数据对象已经添加了字段,我们不会覆盖它。为此,我们会利用已安装的生命周期挂钩。

mounted(){
let dataFromLocalStorage = JSON.parse(localStorage.formSave);
for(const key in dataFromLocalStorage){
this.$data[key] = dataFromLocalStorage[key];
}
}

如果您也想防止刷新,您可以添加onbeforeunload,这将在重新加载事件发生之前捕获它们。然后可以调用$destroy()手动触发销毁生命周期。您可以将其添加到创建的生命周期挂钩或安装的生命周期钩子中。

window.onbeforeunload = () => this.$destroy();

下面是一个关于codesandbox 的工作示例

最新更新