簡體   English   中英

如何在模板中使用$ refs-Vue.js

[英]How to use $refs in template - vuejs

我有一個屬性為“ ref”的輸入,並且我不想使用v模型

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

我想自動顯示輸​​入值。 我做這個

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

但尚未更新。

因為refvalue除非綁定到組件實例,否則不是可觀察的對象:

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

然后給您的input一個:value="name" ,現在它已經附加了一個觀察者。

我不明白您想做什么,但是您做的方式似乎是錯誤的。無論如何,您說我不想使用 v-model

我將向您展示如何在不使用v模型的情況下執行此操作,您可以從api獲取輸入值(您必須為此編寫自己的代碼)並將其設置為輸入:

 <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>

看到它在這里行動

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM