简体   繁体   中英

How to use $refs in template - vuejs

I have a input with attribute "ref" and I don't want to use v-model

<div class="form-group m-b-40">
  <input type="text" class="form-control" id="name" ref="name"  required> 
</div>
 {{showInput}}

I want to show my input value automatically. I do this

 methods: {
       showInput: function () {
            this.$refs.name.value
        },
    }

but it isn't updated.

Because the value of a ref isn't an observable object unless it's bound to the component instance:

data() {
    return {
        name: ''
    }
}

Then give your input a :value="name" and now it has an observer attached to it

I can't understand what you want to do,but the way you are doing it seems to be wrong.Anyway,you said i dont want to use v-model .

I am going to show you how to do it without v-model,you can fetch the input value from api(you have to write your own code for this) and set it to input:

 <template>
    <div>
      <div class="form-group m-b-40">
        <input type="text" :value="text" @input="updateValue"> 
        <hr>
      </div>
      The input value is: {{text}}
    </div>
 </template>

<script>
export default {
  data() {
    return {
        text: ''
    }
  },
  created() {
    this.fetchFromApi()
  },
  methods: {
    updateValue(value) {
        let newValue = value.target.value
        this.text = newValue
    },
    fetchFromApi() {
        //write the code to get from API the input value and then:
      this.text = 'input value' //set the input value
    }
  }
}
</script>

See it in action here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM