【问题标题】:Retain filled form fields on page refresh in Vue在 Vue 中的页面刷新时保留填充的表单字段
【发布时间】:2020-07-28 16:07:18
【问题描述】:

我在这里面临的问题是,我无法弄清楚如何在页面刷新时保留表单中的值。每次我刷新页面时,表单中的所有填充值都消失了。

帮我解决这个问题。我正在考虑使用 localStorage,但不确定如何实现它。

   <template>
     <v-card class="mb-12">
       <v-form :model='user' class="content-padding" ref='pdfInputs'>
            <div class="section-header">
              User
            </div>
            <v-container fluid>
             <ul>
              <li v-for="(input, index) in user.inputs">
               <input type="text" v-model="input.one"> - {{ input.one }}  
               <input type="text" v-model="input.two"> - {{ input.two }}
               <button type="button" @click="deleteRow(index)">Delete</button>
              </li>
             </ul>   
            </v-container>
       </v-form>
     </v-card>
   </template>  


<script>
 export default {
  data () {
    return {
     user: {
      inputs: []
     }
    }
  }
  methods: {
    addRow() {
      this.user.inputs.push({
        one: '',
        two: ''
      })
    },
    deleteRow(index) {
      this.user.inputs.splice(index,1)
    }
  }
 }
</script>

【问题讨论】:

    标签: javascript vue.js local-storage vuetify.js


    【解决方案1】:

    vue中有watch功能

    export default {
      data () {
        return {
         user: {
          inputs: []
         }
        }
      },
      mounted() {
        this.user.inputs = JSON.parse(localStorage.getItem('form')) || [];
      },
      watch: {
            user: {
                handler: function() {
                    localStorage.setItem('form', JSON.stringify(this.user.inputs));
                },
                deep: true
            }
        },
      methods: {
        addRow() {
          this.user.inputs.push({
            one: '',
            two: ''
          })
        },
        deleteRow(index) {
          this.user.inputs.splice(index,1)
        }
      }
     }
    

    【讨论】:

    • 约瑟夫,我试过了。但它不起作用。字段值在刷新时丢失。
    • 你能检查是否触发了处理函数吗?带调试器;还是 console.log?
    • 代替user试试'user.inputs'
    • 是的,我尝试使用 console.log。它被触发。我改为user.inputs。但它仍然没有保留值。
    • 'form' 我们在 setItem 中作为参数传递,这是应该的样子吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-24
    • 1970-01-01
    • 1970-01-01
    • 2015-12-22
    相关资源
    最近更新 更多