2017-08-06 53 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/