2017-08-14 40 views
0

我試圖爲我的應用程序實現搜索組件,父組件具有搜索文本框和按鈕。當用戶提供一些值時,我想將數據發送到api並在子組件中顯示結果。我有點困惑在哪裏調用api以及如何填充子組件中的數據。此外,最初我的孩子組件不應該在父組件中呈現,當搜索得到一些結果,然後它可以呈現。請幫助我如何實現VUE JS搜索功能2.當承諾數據存在時顯示子組件,並且還在子組件中呈現數據

父組件

<template> 
    <div><h3> Search </h3></div> 
    <div class="row"> 
    <form role="search"> 
     <div class="form-group col-lg-6 col-md-6"> 
      <input type="text" v-model="searchKey" class="form-control"> 
     </div> 
     <div class="col-lg-6 col-md-6"> 
      <button type="button" id="btn2" class="btn btn-danger btn-md" v-on:click="getInputValue">Search</button> 
     </div> 
    </form> 
    </div> 
    <result :searchdataShow='searchData'></result> 
</template> 
<script> 
import resultView from './result' 
export default { 
    components: { 
    'result': resultView 
    }, 
data() { 
    return { 
     searchKey: null, 
     searchData: null 
    } 
    }, 
    methods: { 
    getInputValue: function(e) { 
    console.log(this.searchKey) 
    if(this.searchKey && this.searchKey != null) { 
     this.$http.get('url').then((response) => { 
     console.log(response.data) 
     this.searchData = response.data 
     }) 
    } 
    } 
} 
</script> 

搜索結果成分(子組件)

<template> 
    <div> 
    <div class="row"><h3> Search Results</h3></div> 
    </div> 
</template> 
<script> 
    export default { 
    props: ['searchdataShow'] 
    } 
</script> 

回答

0

創建,保持跟蹤一個布爾變量您阿賈克斯請求,我通常稱它爲loadingfetchedData,這取決於上下文。在ajax調用之前,在調用之後將其設置爲true,將其設置爲false。

一旦你有這個變量的工作,你可以有條件地呈現result組件v-if。我喜歡顯示相應的加載圖標v-else

此外,您的模板似乎沒有根元素,這是必需的。

<template> 
    <div><h3> Search </h3></div> 
    <div class="row"> 
    <form role="search"> 
     <div class="form-group col-lg-6 col-md-6"> 
      <input type="text" v-model="searchKey" class="form-control"> 
     </div> 
     <div class="col-lg-6 col-md-6"> 
      <button type="button" id="btn2" class="btn btn-danger btn-md" v-on:click="getInputValue">Search</button> 
     </div> 
    </form> 
    </div> 
    <result v-if="!loading" :searchdataShow='searchData'></result> 
    <div v-else>loading!!</div> 
</template> 
<script> 
import resultView from './result' 
export default { 
    components: { 
    'result': resultView 
    }, 
data() { 
    return { 
     loading: false, 
     searchKey: null, 
     searchData: null 
    } 
    }, 
    methods: { 
    getInputValue: function(e) { 
    console.log(this.searchKey) 
    this.loading = true; 
    if(this.searchKey && this.searchKey != null) { 
     this.$http.get('url').then((response) => { 
     console.log(response.data) 
     this.loading = false; 
     this.searchData = response.data 
     }) 
    } 
    } 
} 
</script>