更新组件

时间:2017-08-06 13:45:52

标签: javascript vue.js vuejs2 vue-component

我很想知道如何更新组件。 所以,这是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>

和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 ?
      }
  }
});

所以,我的目标是创建一个模板,当然还要更新他的数据。 这该怎么做 ? 我创建了一个用于测试的jsfiddle:https://jsfiddle.net/4w0kh30t/1/ 谢谢你的帮助。

1 个答案:

答案 0 :(得分:1)

首先,您需要为您的vue实例提供数据以使您的数据具有反应性。 因此,向您的vueApp添加数据,如下所示:

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 ?
      }
  }
});

现在要进行更改,您需要使用this.person = something,这将是您在提交事件方法中的结果,如下所示:

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

现在,您的组件对更改作出反应,它必须通过属性或道具接收数据。将组件更改为:

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

最后,您需要将 person 传递给vue实例模板中的组件:

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

结果在这里:

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

相关问题