<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>我想用这份代码在hbuilderx的vue上实现点击保存按钮后输入的姓名会永久保存在本地地址里
时间: 2024-04-17 08:27:03 浏览: 83
你可以使用本地存储(localStorage)来实现将输入的姓名永久保存在本地地址里。在保存成功后,将姓名存储到localStorage中,然后在组件加载时从localStorage中读取姓名并赋值给`mineFormData.name`。
下面是修改后的代码示例:
```vue
<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中。在组件加载时,如果localStorage中存在姓名,则会从localStorage中读取并赋值给`mineFormData.name`,从而实现了姓名的永久保存。
阅读全文