Home > Blockchain >  Data in vue2 disappearing
Data in vue2 disappearing

Time:06-19

I did a simple page with vue2, it is a binary to decimal conversor. But when I submit the binary value when it is in a HTML form de data disappears. The component

<template>
    <div >
        <input id="str" type="text">
        <button type="submit" @click="toArray">Converter</button>
        <div id="exit">{{dec}}</div>
    </div>
</template>

<script>
export default {
    data(){
        return {
            arr: [],
            dec: ''
        }
    },
    methods: {
        toArray(){
            let str = document.getElementById('str').value;
            var myArr = String(str).split("").map((str)=>{
                return Number(str)
            })
            this.arr = myArr;

            let decimal = 0;
            for(let i = 0; i < this.arr.length; i  ){
                decimal = decimal   (this.arr[i]*(2**(this.arr.length-i-1)))
            }                   
            this.dec = decimal
        }
    }
}
</script>

The vue page where the component is called

<template>
    <form >
        <div >
            <div>
                <conversor/>
            </div>
        </div>
    </form>
</template>

CodePudding user response:

Your component is in form so you need to stop submit, try with @click.prevent, and you can use v-model for your input:

Vue.component('conversor', {
  template: `
    <div >
      <input v-model="val" type="text">
      <button type="submit" @click.prevent="toArray">Converter</button>
      <div id="exit">{{ dec }}</div>
    </div>
  `,
  data(){
    return {
      arr: [],
      dec: '',
      val: ''
    }
  },
  methods: {
    toArray(){
      this.arr = String(this.val).split("").map((str)=>{
        return Number(str)
      })

      let decimal = 0;
      for(let i = 0; i < this.arr.length; i  ){
        decimal = decimal   (this.arr[i]*(2**(this.arr.length-i-1)))
      }                   
      this.dec = decimal
    }
  }
})

new Vue({
  el: '#demo',
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="demo">
  <form >
    <div >
      <conversor/>
    </div>
  </form>
</div>

  • Related