1

I have an input which is bidden to property message. I have a set button , which I use for changing of input value programmatically. When the button is pressed, value of input is correctly changed to 'xxxx'. when I press clean button after that , the input is correctly cleaned but when I repeat pressing set and clean again the input does not get cleared anymore.

Working example is here:

https://codepen.io/dan-ouek/pen/rNBjxRO

<div class="container">
  <div id='root' class="box">
    <input ref="templateFilter" type='text' id='input' v-model='message'>
    {{ message }}
    <button @click="set">set</button>
    <button @click="clean">clean</button>
  </div>
</div>
new Vue({
  el: '#root',
  data: {
    message: 'Hello Vue'
  },
  methods: {
    set: function () {
       let element = this.$refs.templateFilter
       Vue.set(element, 'value', 'xxxx')
  }, clean: function () {
      this.message = ""
  }
}})

Questions:

1) Is it possible to change input programmatically without working with bidden property value? Something like direct DOM manipulation:

let element = document.getElementsByClassName("templateFilter")[0]
element.value = 'xxxxx'

but with proper component refresh?

2) Why is the {{ message }} not refreshed after calling set method?

1
  • 2
    why not just this.message = "xxxx" inside the set method Commented Aug 23, 2019 at 13:09

1 Answer 1

1

Why is the message not refreshed after calling set method?

When you type something on your input the message data gets updated via an event handler BUT when you set it programmatically the event handler is NOT triggered and that's why message was not getting updated / refreshed....

Solution :

a short solution to your issue would be just to mutate the message value this.message = "xxxx" but if you insist on making that programmatically you have to trigger the input event :

set: function() {
  let element = this.$refs.templateFilter
  Vue.set(element, 'value', 'xxxx')
  element.dispatchEvent(new Event('input'))
}

Here is a Demo : codepen

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.