JeffProd
JeffProd

Reputation: 3148

Update component

I am missunderstanding how to update a component. So, here is the HTML :

<div id="app">

  <form v-on:submit="submitForm">
    <input type="text" id="txtSearch">
    <input type="submit" value="go">
  </form>

  <br><br>

  <user></user>

</div>

And the JS :

let userComponent = {
    template: 'your name is : {{name}}<br>You are {{age}}'
    };

let vueApp = new Vue({
  el: '#app',

  components: {'user': userComponent},

  methods: {
    submitForm: function(e) {
      e.preventDefault();
      let val = document.getElementById('txtSearch').value;
      alert('submitted : ' + val);
      // normally i do a search here : let result = mySearch(val);
      // but let's do the job with this :
      let result = {name: 'John', age: 27};
      // so now, how to modify the <user> with this data result ?
      }
  }
});

So, my aim is to create a template, and of course update his data. How to do this ? I created a jsfiddle for testing : https://jsfiddle.net/4w0kh30t/1/ Thanks for your help.

Upvotes: 1

Views: 628

Answers (1)

Lucas Katayama
Lucas Katayama

Reputation: 4570

First, you need a data for your vue instance to make your data reactive. So add to your vueApp a data, like so:

let vueApp = new Vue({
  el: '#app',
  data: {
     person: {
         name: '',
         age: 0,
     }
  }
  components: {'user': userComponent},
  methods: {
    submitForm: function(e) {
      e.preventDefault();
      let val = document.getElementById('txtSearch').value;
      alert('submitted : ' + val);
      // normally i do a search here : let result = mySearch(val);
      // but let's do the job with this :
      let result = {name: 'John', age: 27};
      // so now, how to modify the <user> with this data result ?
      }
  }
});

Now to make changes you need to use this.person = something, which womething will be your result in the submit event method, like this:

submitForm: function(e) {
      e.preventDefault();
      let val = document.getElementById('txtSearch').value;
      alert('submitted : ' + val);
      // normally i do a search here : let result = mySearch(val);
      // but let's do the job with this :
      let result = {name: 'John', age: 27};
      this.person = result
    }
 }

Now, to your component react to changes it must receive data through properties or props. Changing component to this:

let userComponent = {
    props: ['user'],
    template: 'your name is : {{name}}<br>You are {{age}}'
};

In the end, you need to pass person to the component in the template of vue instance:

<user :user="person"></user>

The result is here:

https://jsfiddle.net/jhs7ffch/1/

Upvotes: 1

Related Questions