<template> <uni-forms ref="mineForm" :rules="mineRules" :modelValue="mineFormData"> <uni-forms-item label="姓名" :required="true" name="name"> <uni-easyinput v-model="mineFormData.name" placeholder="请输入姓名"></uni-easyinput> </uni-forms-item> </uni-forms> <button type="primary" size="mini" @click="save('mineForm')">保存</button> </template> <script> export default { data() { return { mineFormData: { name: '', }, mineRules: { name: { rules: [ { required: true, errorMessage: '姓名不能为空', }, ], }, onReady() { this.$refs.mineForm.setRules(this.mineRules) }, methods: { save(ref) { this.$refs[ref].validate().then(res => { console.log('success', res); uni.showToast({ title: '保存成功' }) }).catch(err => { console.log('err', err); }) } } } </script>我想用这份代码实现点击保存按钮后输入的姓名会永久保存在本地地址里
时间: 2024-02-10 21:27:54 浏览: 198
你可以使用浏览器的本地存储(localStorage)来实现将输入的姓名永久保存在本地。在保存成功后,将姓名存储在localStorage中,后在页面加载时从localStorage中获取已保存的姓名并显示在输入框中。下面是修改后的代码示例:
```html
<template>
<uni-forms ref="mineForm" :rules="mineRules" :modelValue="mineFormData">
<uni-forms-item label="姓名" :required="true" name="name">
<uni-easyinput v-model="mineFormData.name" placeholder="请输入姓名"></uni-easyinput>
</uni-forms-item>
</uni-forms>
<button type="primary" size="mini" @click="save('mineForm')">保存</button>
</template>
<script>
export default {
data() {
return {
mineFormData: {
name: localStorage.getItem('name') || '', // 从localStorage中获取已保存的姓名
},
mineRules: {
name: {
rules: [
{
required: true,
errorMessage: '姓名不能为空',
},
],
},
},
};
},
methods: {
save(ref) {
this.$refs[ref].validate().then(res => {
console.log('success', res);
localStorage.setItem('name', this.mineFormData.name); // 将姓名保存在localStorage中
uni.showToast({
title: '保存成功',
});
}).catch(err => {
console.log('err', err);
});
},
},
};
</script>
```
通过使用`localStorage.setItem('name', this.mineFormData.name)`将姓名保存在localStorage中,并使用`localStorage.getItem('name')`从localStorage中获取已保存的姓名。这样,当页面加载时,输入框会自动填充已保存的姓名。
阅读全文