Vuejs Router-View and Axios

Asked

Viewed 815 times

3

I have a page with 2 structures using router-view. Menu and Content. the in my Menu I have a page called "Shops", on that page "Shops" has a table, I give a Axios.Get in my API and it returns me a JSON that plays to the table "Shops".

Problem: If my API has a new datum, I have to reload the view.

Solution that I would like: When I click there on the menu in the item "Shops", i wanted the current view (in case "Shops") reload for Axios to give the Get again and the Table to bring the current data.

@EDIT

Shops.

<template>
    <table class="table table-bordered table-striped dataTable" id="dataTable" width="100%">
       <tbody class="animated fadeIn">
          <tr v-for="item in dataItem" v-bind:key="item.Id">
             <td class="text-left">{{item.Name}}</td>
          </tr>
       </tbody>
    </table>
</template>

<script>
import axios from 'axios'
    export default {
        data: () => ({
            dataItem: [],
            errors: []
         }),
        created() {
            axios.get(`http://localhost:8090/API/Lojas`)
                .then(response => {
                    this.dataItem = response.data.Data
                }).then(() => {
                    $('#dataTable').DataTable( datatableConfigBR )
                })
                .catch(e => {
                    this.errors.push(e)
                })
        }
    }
</script>

Menu.

<ul class="nav nav-second-level collapse">
   <li>
      <router-link :to="{ name: 'lojas' }">Lojas</router-link>
   </li>
</ul>

Routes.js

import lojas from './Lojas.vue'

const routes = [{
        path: '/Content',
        component: Content,
        children: [
            {
                name: "lojas",
                path: '/Lojas',
                component: lojas
            }
        ]
    }
]

Thank you!

2 answers

5


Usa one of the methods that the vue-router implements in the component, the beforeRouteEnter.

Those hooks/ pre-defined hooks such as the beforeRouteEnter are called before the route is redecorated, and in this case pass a function to callback next this function is called when the component has been instantiated and is available within that function.
At that moment you can call the function methods.

Example:

import axios from 'axios'
export default {
  data: () => ({
    dataItem: [],
    errors: []
  }),
  methods: {
    atualizarLoja() {
      axios.get(`http://localhost:8090/API/Lojas`)
        .then(response => {
          this.dataItem = response.data.Data
          $('#dataTable').DataTable(datatableConfigBR)
        })
        .catch(e => {
          this.errors.push(e)
        })
    }
  },
  beforeRouteEnter(to, from, next) {
    next(vm => vm.atualizarLoja())
  }
}

jsFiddle: http://jsfiddle.net/Sergio_fiddle/Ly4eaeyq/

If you want to force the update of the component while already in the view of that component the router does not help you. If there is no navigation the router does nothing.

In this case the best possibility is to create an update button, or change the click button in the menu for a component that calls the method.

That last idea would be like this: http://jsfiddle.net/Sergio_fiddle/Ly4eaeyq/1/

  • Sergio, I was wondering how this code works, could you explain? always learning from you rs

  • @Rafaelaugusto I edited the rereader with an example. My initial answer followed an answer of one of the core-developers but I couldn’t implement, I think it would be the version 1.x. Now corrected and gave an example. Thank you for the request for explanations, so corrected my reply :)

  • @Sergio understood what he did! but I fall into the same problem as Rafael’s example, The call from Axios API is in Shops., and this Click Method would have to stay in my Menu.. How do I do in this problem? Thank you!!

  • @Jackson this method that updates the store is called whenever you open this page. That’s not what you want?

  • Yes, it already works in the Created() property. I wanted to recall the Axios method when I click on the menu page. It’s like a Refresh from the page. It’s like I’m in Stores.Go to the Menu and click on "Stores" to bring the data. Today I have to go to another view, and go back to "Shops" for the Axios give the Get again

  • @Jackson ok. I edited the answer. Take a look and test the second jsFiddle

  • Got it @Sergio! Thanks for the help. It was very clear =)

Show 2 more comments

1

You don’t need to reload the view, just have a method and call it whenever you click, or even reload it in x minutes. Ex:

<script>
   export default{
      data(){
         return{
            dados: []
         }
      },
      methods: {
         api(){
            axios.get('URL')
            .then(response => {
                this.dados = response.data
            })
            .catch(error => {
                console.log('ERRO')
            })
         }
      }

   }
</script>

and ai on a link <button @click="api">Atualizar</button>

Or even in X time

<script>
   export default{
      data(){
         return{
            dados: []
         }
      },
      created(){
          this.api()
      },
      methods: {
         api(){
            setInterval(function(){
            axios.get('URL')
            .then(response => {
                this.dados = response.data
            })
            .catch(error => {
                console.log('ERRO')
            })
            }, 1000)
         }
      }

   }
</script>
  • I really liked your alternative, but the problem is that the Axios API call is on Shops., and this Click Method would have to stay in my Menu..

Browser other questions tagged

You are not signed in. Login or sign up in order to post.