簡體   English   中英

Vue JS:如何使用從父 Vue 下拉列表中選擇的值從子組件調用 Axios ApI

[英]Vue JS : How to make Axios ApI call from Child component using Value Chosen from Parent Vue Dropdown

我有父組件,它將貨幣值作為下拉組件,並且有子組件應該根據從父貨幣下拉列表中選擇的值動態調用 AXIOS API。 下拉值將從父組件動態更改。 但是 axios API 呼叫將僅由孩子完成。 我使用 $emit 使用了以下方法。 但似乎沒有任何效果。 同樣在子組件父下拉列表中再次出現(重復)。 想要阻止它。 所以我需要以下兩件事

  1. 防止由於導入父組件而出現在子級上的下拉菜單
  2. 如何在子級獲取值以獲取父級更改的值

父組件.vue

<select  @change="sendChange" class="form-select">
    <option value="">Select a Currency</option>
    <option v-for="(currency, index) in currencyList" :value="currency.code" :key="index">
      {{ currency.currencyCode}}
    </option>
  </select>

  <script>
    export default {
    data() {
        return {
           currencyList :[],
            currentcyChosen: ' ',
        };
    },
   sendChange(event) {
            this.currentcyChosen = event.target.value;
            //this should be used at parent
            this.$emit("currencyChange", this.currentcyChosen);
            alert("capturing emit");
            alert(this.currentcyChosen);
        }
 </script> 

子組件.vue

   <template>
    <ParentComponent v-on:currencyChange ="getCurrencyChosenFromParent" />
   </template>

  <script>
    import axios from 'axios';
    import ParentComponent  from './ParentComponent.vue';
    data() {
        return {
            localCurrency: ' ',
        };
    },
    getCurrencyChosenFromParent(){
      alert("got currency from Parent);
      //this should be fetched from Parent
      alert(this.localCurrency);
      //Make Axios call from child based upon currencyChange
    }
    </script>'''

希望下面的代碼對你有所幫助。

父組件.vue:

  <select
    @change="sendChange"
    class="form-select"
  >
    <option value="">Select a Currency</option>
    <option
      v-for="(currency, index) in currencyList"
      :value="currency.code"
      :key="index"
    >
      {{ currency.currencyCode}}
    </option>
  </select>
</template>

<script>
export default {
  data () {
    return {
      currencyList: [
        {
          'code': 1,
          'currencyCode': 'one'
        },
        {
          'code': 2,
          'currencyCode': 'two'
        },
        {
          'code': 3,
          'currencyCode': 'three'
        },
      ],
      currentcyChosen: ' ',
    };
  },
  methods: {
    sendChange (event) {
      this.currentcyChosen = event.target.value;
      this.$emit("currencyChange", this.currentcyChosen);

    }
  }
}
</script>

ChildComponent.vue:

<template>
  <parent-components @currencyChange="(n) => localCurrency = n" />
  <p>{{localCurrency}}</p>
</template>

<script>
import parentComponents from './parentComponents.vue';
export default {
  components: { parentComponents },
  data () {
    return {
      localCurrency: '',
    };
  },
}
</script>





暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM