Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change a Vue.js data value within a method called by a DOM event?

Disclaimer: I know that there is data biding in Vue.js.

So I have this:

<html>
<body>

    <div id="app">
        <input @input="update">
    </div>

    <script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
    <script type="text/javascript">

        new Vue({

            el: '#app',

            data: {

                info: '',

            },

            methods: {

                update: function (event) {

                    value = event.target.value;

                    this.info = value;
                    console.log(value);

                }

            }

        });

    </script>

</body>
</html>

An input that will trigger a method called update every time the user type in something. The idea here is to change the value of the data property called info with the value typed in the input by the user.

But, for some reason, the value of the data attribute doesn't change. The current input value is printed normally in the console with the console.log(value) call every time the update method is fired, but nothing changes to the info attribute.

So, how to make this work?

like image 935
Artenes Nogueira Avatar asked Jan 28 '17 00:01

Artenes Nogueira


People also ask

How does Vue reconcile changes to the DOM?

When virtual nodes start to change Vue compares the new and the old state and decides if the DOM needs to be updated. This process is called reconciliation. If a change is required only the associated DOM nodes will be altered with the rest of the tree to remain intact.

How do you access data in Vue methods?

To access to data from methods with Vue. js, we can use reactive properties. export default { data() { return { questions: [], sendButtonDisable: false, }; }, methods: { postQuestionsContent() { this. sendButtonDisable = true; }, }, };

What is click stop Vue?

prevent is a modifier for v-on:click . Another handy modifier is . self , which tells Vue to only evaluate v-on:click if the element itself is clicked, as opposed to one of its children. For example, Vue only calls the below v-on:click handler when you click on the outer div , not the inner div .


1 Answers

I'm not seeing what your problem is; your example works perfectly:

new Vue({

  el: '#app',

  data: {

    info: '',

  },

  methods: {

    update: function(event) {

      value = event.target.value;

      this.info = value;
      console.log(value)
    }

  }

});
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<div id="app">
  <input @input="update">
  {{ info }}
</div>
like image 145
RyanZim Avatar answered Oct 06 '22 11:10

RyanZim