[Vuejs]-Need help using Vue methods in routed templates

0👍

You can get vue-router to pass any params offered into component props using props: true.

This way, you can construct your <router-link> elements with any extra data you want. All you have to do is pass in params. This is best facilitated by using a named route, eg

<router-link :to="{ name: 'Level', params: { id: 1, say_hello: 'whatever' } }">

For example

const Home = { template: 
  `<div class="container">
    I'm leaving some stuff out, but routing works fine in the real code
  </div>`
};

const Level = { template:
  `<div class="container">
    <h2>Level {{ id }}</h2>
    {{ say_hello }}
  </div>`,
  props: {
    id: [String, Number],
    say_hello: {
      default: 'Nobody said hello 😦'
    }
  }
}

// === Define our routes ===
const router = new VueRouter({
    routes: [
        { path: '/', name: 'Home', component: Home, props: true },
        { path: '/level/:id', name: 'Level', component: Level, props: true }
    ]
})

// === Now fire up Vue and display it on screen ===
const vm = new Vue({
  el: '#app',
  router,
  data: () => ({
    say_hello: 'hello'
  })
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.min.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<div id="app">
<router-view></router-view>
<p>
  <router-link :to="{ name: 'Level', params: { id: 1, say_hello } }">Level 1</router-link>
</p>
<pre>$route.fullPath = {{ $route.fullPath }}</pre>
</div>

Leave a comment