1

In my Vue app, I have a timer and a text field.

When I try to decrease the remaining seconds, the changes I make in the field keep disappearing. The timer and the field are completely unrelated.

Here's a simple demo, write anything to the field:

https://codepen.io/basabence/pen/jObwqgL

<div id="app">
    <span>Time: {{remaining_time}}</span><br>
    <input :value="step_answer" type="text">
</div>

app = new Vue({
  el: '#app',
  data: {
    remaining_seconds: 60,
    step_answer: "asdasd",
  },
  created: function (){
    setInterval(()=>{
      this.remaining_seconds--
    },1000);
  }
})

Interestingly if I change the :value to v-model, it works fine - but I don't want to bind this field two-way... Have any of you met this behaviour before?

Thank you in advance

ben3000
  • 4,629
  • 6
  • 24
  • 43
Bence Basa
  • 11
  • 2

2 Answers2

2

You get this behavior because data is a reactive object. When you bind the value with step_answer, you create one-way binding data -> component, which means step_answer is the master.

To achieve Two-way binding without v-model you need to capture @input event and append it or assign step_master with the new value.

<input
  v-bind:value="step_answer"
  v-on:input="step_answer = $event.target.value">

Full example :

<div id="app">
    <span>Time: {{remaining_seconds}}</span><br>
    <input
  v-bind:value="step_answer"
  v-on:input="appendValue($event)">
</div>


app = new Vue({
  el: '#app',
  data: {
    remaining_seconds: 60,
    step_answer: "asdasd",
  },

  created: function (){
    setInterval(()=>{
      this.remaining_seconds--
    },1000);
  },
  methods:{
    appendValue(e){
      this.step_answer=e.target.value;
    }
  }
})
  • It just hit me: that's what v-once is created for !! Thanks for the breadcrumbs, I was stuck with this for hours... – Bence Basa Apr 27 '20 at 21:56
1

:value, a one way binding, will never let the input from your keyboard update the state of the component. That is why v-model exists. Check out this question and answers for more details.

LShapz
  • 1,738
  • 11
  • 19
  • 1
    But I don't want the model to be updated... I just need the variable in the value :) – Bence Basa Apr 27 '20 at 21:48
  • I need the value as well; I'm trying to avoid any binding because that invokes DOM re-render (which invokes other render logic). – Kalnode Jul 22 '22 at 14:10