繁体   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