2017-08-06 46 views
1

我误解如何更新组件。 所以,这里是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/ 感谢您的帮助。

+0

你的问题和这个[SO问题]非常相似(https://stackoverflow.com/questions/42694457/getting-form-data-on-submit) 。你可以像这样[小提琴](https://jsfiddle.net/awolf2904/4w0kh30t/4/)。 – AWolf

回答

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,这womething将是你的结果在提交事件方法的变化,这样的:

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

最后,你需要传递到组件中VUE实例的模板:

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

其结果是在这里:

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