Use data from the Vue instance in the Vue Router template

2

How to use data from the Vue instance in the templates of Vue Router routes.

This is my code

HTML

 <div id="app">
        <router-link to="/foo/1">ruta 1</router-link>
        <router-link to="/foo/2">ruta 2</router-link>

        <router-view></router-view>        
  </div>

Javascript

Vue.use(VueRouter);

    const Ruta1 = { template: '<div>{{ $route.params.numruta }}</div>' };
    const Ruta2 = { template: '<div>{{ $route.params.id }}</div>' };
    const router = new VueRouter({
        routes: [
            { path: '/foo/:numruta', component: Ruta1 },
            { path: '/foo/:numruta', component: Ruta2 }
        ]
    });
    const app = new Vue({
        router,
        el: "#app",
        data:{ 
            usuario:"nombre de usuario"
        }
    }).$mount('#app');

In that case, use the usuario element in the templpate of Ruta1

    
asked by Emiliano Pamont 19.08.2018 в 06:02
source

1 answer

3

As it is, it could make your work easier by accessing the instance from the component, with this.$root , from here, you have access to your methods and data declared in your instance.

Ejm

Vue.use(VueRouter);
const Ruta1 = { template: '<div>{{this.$root.usuario }}</div>' };
const Ruta2 = { template: '<div>Hola {{this.$root.op }}</div>' };
const router = new VueRouter({
    routes: [
        { path: '/foo/:numruta', component: Ruta1 },
        { path: '/fooo/:numruta', component: Ruta2 }
    ]
});
const app = new Vue({
    router,
    el: "#app",
    data:{ 
        usuario:"Dev. Joel",
        op:"Emiliano",
    }
}).$mount('#app');
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<div id="app">
    <router-link to="/foo/1">Usuario</router-link>
    <router-link to="/fooo/2">OP</router-link>

    <router-view></router-view>        
</div>

Although you could also use props of defined routes to pass values directly.

Vue.use(VueRouter);
const Ruta1 = { props: ['usuario'] , template: '<div>Hola {{ usuario }}</div>' };
const Ruta2 = { props: ['usuario'] , template: '<div>Hola  {{ usuario }}</div>' };

const router = new VueRouter({
    routes: [
        { path: '/uno', component: Ruta1 , props: { usuario: 'StackOverFlowEs' }},
        { path: '/dos', component: Ruta2 , props: { usuario: 'StackOverFlowEn' } }
    ]
});
const app = new Vue({
    router,
    el: "#app"
}).$mount('#app');
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<div id="app">
    <router-link to="/uno">Ruta 1</router-link>
    <router-link to="/dos">Ruta 2</router-link>

    <router-view></router-view>        
</div>
    
answered by 19.08.2018 / 08:35
source