Home » vue » can't write api method in data() vue

can't write api method in data() vue

Posted by: admin November 26, 2021 Leave a comment

Questions:

I want USD to be taken from api which function I’ve in methodsbut how can I write it ?

  data(){
      return {
        posts: 1,
        USD:changeCurrency()
      }
  },
  methods: {
    changeCurrency: function () {
      axios.get('http://data.fixer.io/api/latest?access_key=509c9d50c1e92a712be9c8f1f964cf67')
      .then(response => {
        this.posts = response.data.rates.GEL.toFixed(3)
      })
    }
Answers:

That is not how data is supposed to be used.

You can call changeCurrency in mounted or in the component itself @click="changeCurrency"

{
    data() {
        return {
            posts: 1,
            // USD:changeCurrency()
        };
    },
    mounted() {
        // you could call here instead
        this.changeCurrency();
    },
    methods: {
        changeCurrency: function () {
            axios.get('http://data.fixer.io/api/latest?access_key=509c9d50c1e92a712be9c8f1f964cf67')
                .then(response => {
                    this.posts = response.data.rates.GEL.toFixed(3);
                });
        }
    }
}