Search code examples
javascriptvue.jsccxt

Vue prop default value not working properly


Ok so I have the following prop that I get from the parent component

 props: {
  selectedExchange: {
    default: 'acx',
  }
},

And i try to use it in the following method

 methods: {
  getMarkets() {
    const ccxt = require('ccxt')
    const exchanges = ccxt.exchanges;
    let marketPair = new ccxt[this.selectedExchange]()
    let markets =  marketPair.load_markets()
    return markets
  }
},

The expected result should be an array of markets for my project but i get an error in the console

 [Vue warn]: Error in mounted hook: "TypeError: ccxt[this.selectedExchange] is not a constructor"

Now i thought it might be a problem with ccxt but it's not! I have tried the following code

methods: {
  getMarkets() {
    const ccxt = require('ccxt')
    const exchanges = ccxt.exchanges;
    let acx = 'acx'
    let marketPair = new ccxt[acx]()
    let markets =  marketPair.load_markets()
    return markets
  }
},

If you don't see the change I have made a variable that contains 'acx' inside, exactly the same like the prop but this time it's created inside the method, and with this code I get the expected result, It has been bugging me for days and I can't seem to find an answer to it, did I initialize the default value wrong? When i look inside vue dev tools the value for my prop is array[0], only after I pass a value to that prop it gets updated, shouldn't i see the default value of acx in devtools? Any help is much appreciated!

Edit 1: Added parent component code

This is how i use the methods inside the parent and how my components are related to each other,

<div id="exchange">
  <exchange v-on:returnExchange="updateExchange($event)"></exchange>
</div>
<div id="pair">
  <pair :selectedExchange="this.selectedExchange"></pair>
</div>

And this is the code inside the script tags, i didn't include the import tag cause i don't think it would be useful

export default {
  name: 'App',
  components: { exchange, pair, trades },
  data(){
    return{
      selectedExchange: ''
    }
   },
   methods: {
     updateExchange(updatedExchange){
       this.selectedExchange = updatedExchange
     }
   },
  };

Solution

  • In this case you will inherit the default value:

    <pair></pair>
    

    In this case you will always inherit the value of selectedExchange, even if it's null or undefined:

    <pair :selectedExchange="this.selectedExchange"></pair>
    

    So, in your case, you have to handle the default value on parent component.

    This should work:

    export default {
      name: 'App',
      components: { exchange, pair, trades },
      data(){
        return{
          selectedExchange: 'acx' // default value
        }
       },
       methods: {
         updateExchange(updatedExchange){
           this.selectedExchange = updatedExchange
         }
       },
      };