Problems Vue js and api

1

I'm doing a SPA with Vuejs, (router and axios) I'm trying to get an id of a json object called from an API, for when I click on this feature, that is, I have my APi of https://adventuretimeapi.herokuapp.com/places adventure time and I want when I click to know residents I get info from the residents but when I'm trying to get it I said undefined

What can I do, I've gone around the code and my brain does not know which is the best way, that's why I come here.

This is my code I'm trying with the Pokemon api that has simpler id

<template>

    <router-view v-bind:people="PeopleMain" the-title="Where do you wanna go">
    </router-view>
</template>

<script>

    import personDisplay from './person-display.vue';

    export default {
      name: 'app',
      data() {
        return {PeopleMain: []};
      },
      components: { 

        'person-display' : personDisplay
      },
      created: function() {
        var vm = this;
        axios.get('http://pokeapi.co/api/v2/pokemon/')
        .then(function(response){

            vm.PeopleMain = response.data.results;

            console.log(response.data.results);

            // for (var i=0; i<response.data.length; i++ )
            // {
            //   console.log(vm.PeopleMain[i].residents)
            // }
          for(var i = 0; i<response.data.length; i++) {
             vm.PeopleMain[i].newPlacesId = vm.PeopleMain[i].species.url;



           }



 })
      }

    }
</script>

<style lang="scss">
</style>

The router link

<p><router-link :to="'/type/${person.newPlacesId}'">
    City Info
    </router-link></p>

And where the information will be displayed

<template>
  <div>
    <h1>Detail</h1>
    <p>Name: {{resident.name}}</p>
    <p>Fullname: {{resident.fullname}}</p>

  </div>  
</template>

<script>
  import PersonDiplayPlace from './person-display-place.vue';
  import PersonDiplay      from './person-display.vue';

  export default {
    name: 'resident',
    data() {
      return {resident: {}}
    },
    created() {

      var vm = this;
      var id = this.$route.params.id;
      axios.get('https://pokeapi.co/api/v2/type/${id}/?format=json')
      .then(function(response){
        vm.resident = response.data
        console.log(response.data)
      })


    }

  }

</script>

<style lang="scss">

</style>

I would appreciate if someone could give me a guide, thank you very much for the attention

    
asked by Bella 19.02.2018 в 14:26
source

1 answer

1

As you are a bit confused about how to perform this process, I will add a base example for these requests and how to render through components using Single File Component , all this using the API in heroku

First you must have an input file to configure vue-router with their respective routes. It would have the following content.

Index.js

import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter)

import  index from './components/index';
import  places from './components/places';

//Definimos las rutas y los componentes respectivos
const routes = [
    { path: '/', component: index },
    { path: '/places/:id', component: places , name :'pokemonunico'}
]

const router = new VueRouter({
  routes
})

const app = new Vue({
  router,
}).$mount('#app')

Then the index.js components, I added a% basic% co with nav , we obtain the data from the API, and iterate with bootstrap 4 and create the v-for .

<template>

    <nav class="navbar navbar-expand-lg navbar-light bg-light">
      <a class="navbar-brand" href="#">API VueJs</a>
      <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
        <span class="navbar-toggler-icon"></span>
      </button>

      <div class="collapse navbar-collapse" id="navbarSupportedContent">
        <ul class="navbar-nav mr-auto">
          <li class="nav-item active">
                 <router-link to="/" class="nav-link">Inicio</router-link>
              </li>
              <!-- Enlaces a cada uno de los items obtenidos desde la API
              para el parámetro se emplea el método getId para retornar la última parte
              de la URl para posteriromente hacer la Petición -->
              <li v-for="item in items"  class="nav-item"><router-link  class="nav-link" :to="{ name: 'pokemonunico', params: { id: getId(item.url) }}" >{{item.name}}</router-link></li>
        </ul>
      </div>
    </nav>


</template>

<script>
    export default {
        name: 'index',
        data () {
            return {
                items : []
            }
        },
        created(){
            var vm = this;
            axios.get('https://adventuretimeapi.herokuapp.com/places/')
            .then(function(response){
                // Asignamos el Array retornado
                vm.items = response.data;
            }).catch(function (error) {
                console.log(error);
            });
        },
        methods : {
            // método para obtener la última parte de la URL
            getId : function(item){
                let url = item.split('/');
                return  url.pop() || url.pop();
            }
        }
    }
</script>

And finally the component places.js , access to data is basic. from that in the array route-link you will have everything that returns your item , and you can access the properties you want or create more components.

<template>

    <div>
        <div v-if="item.length ===0"> Cargando...</div>
        <div v-if="item.length !==0">
            <h5> Nombre </h5> 
            <p>{{ item.name}}</p>
            <h5> Residentes </h5> 
            <ul>
                <li v-for="el in item.residents">{{ el}}</li>
            </ul>
        </div>
    </div>
</template>

<script>
    export default {
        name: 'places',
        data () {
            return {
                item : []
            }
        },
        created(){
            var vm = this;
            // Obtenemos la información de ese id pasado por parámetro
            // y se le asigna al array item , con esto ya podrá acceder a todas 
            // las propiedades del Array
            axios.get('https://adventuretimeapi.herokuapp.com/places/' + this.$route.params.id)
            .then(function(response){
              vm.item = response.data;
            }).catch(function (error) {
                console.log(error);
            });
        }
    }
</script>

As additional information if you use API you will know that there is a Laravel file where you import bootstrap.js and others, it will be necessary to add a configuration for the axios , adding a new key of the one that already exists .

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
window.axios.defaults.headers.common['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf8';

And remove or comment where the headers is added to the headers since it is not necessary, that is

window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
    
answered by 19.02.2018 / 18:24
source