Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vue.js/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 更新组件_Javascript_Vue.js_Vuejs2_Vue Component - Fatal编程技术网

Javascript 更新组件

Javascript 更新组件,javascript,vue.js,vuejs2,vue-component,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&

我不理解如何更新组件。 下面是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 ?
      }
  }
});
let userComponent={
模板:“你的名字是:{{name}}
你是{{age}” }; 让vueApp=新的Vue({ el:“#应用程序”, 组件:{'user':userComponent}, 方法:{ 提交形式:函数(e){ e、 预防默认值(); 让val=document.getElementById('txtSearch').value; 警报(“已提交:”+val); //通常我在这里进行搜索:让result=mySearch(val); //但让我们用这个来做这项工作: 让结果={name:'John',年龄:27}; //那么现在,如何使用此数据结果修改? } } });
所以,我的目标是创建一个模板,当然还要更新他的数据。 如何做到这一点? 我创建了一个用于测试的JSFIDLE: 感谢您的帮助。

首先,您需要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 ?
      }
  }
});
现在,为了让组件对更改做出反应,它必须通过属性或道具接收数据。将组件更改为此:

let userComponent = {
    props: ['user'],
    template: 'your name is : {{name}}<br>You are {{age}}'
};
let userComponent={
道具:['user'],
模板:“你的名字是:{{name}}
你是{{age}” };
最后,您需要将person传递给vue实例模板中的组件:

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

结果如下:


您的问题与此非常相似。你可以这样做。
<user :user="person"></user>