Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vuejs Router, conditional loading of JavaScript Code

I am integrating Vue Router into my application.

Within one of my components, I am using some js code which I do not want to load or be present when on another route?

Example

compA.vue
<script>console.log('hello')</script>

app.com/a -> I should see console log Hello.

app.com/b -> when I access this I should not see hello in the console.

EDIT: Clarifying based on the responses.

I have two components, each with own lifecycle hooks so I do not need to set logic to fire the function based on components...

If a user visits compA and the function fires and creates some side effects, when I visit compB I would like there to be no side effects similar to how a traditional route would work, because it would get the new code and render the page once more.

like image 474
dendog Avatar asked Jul 16 '18 14:07

dendog


2 Answers

You could use the path variable accessible through $router in vue. Open your vue devtools, click on your component and click on $route on the righthandside. Here you can see all the variables accessible through $route

Example:

  mounted() {
    // console.log will only run on route '/a'
    if (this.$route.path === '/a') {
        console.log('Hello World)
    }
  }

If $route throws an error. You need to define this in your main.js

  import router from './router'

  new Vue({
    el: '#app',
    router,
    store,
    render: h => h(App)
  })

in router/index.js

import Vue from 'vue'
import Router from 'vue-router'
import Login from '@/app/Login/Login'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Login',
      component: Login
    }
  ]
})
like image 174
Odyssee Avatar answered Sep 28 '22 14:09

Odyssee


you can add some meta data to your routing config:

const router = new VueRouter({
  routes: [
    {
      path: '/a',
      component: compA,
      meta: { doLog: true }
    },
    {
      path: '/b',
      component: compA,
      meta: { doLog: false }
    },
  ]
})

and then you can use this.$route.meta.doLog in your component:

created() {
  if(this.$route.meta.doLog) {
     console.log('hello');
  }
}
like image 44
Andrey Avatar answered Sep 28 '22 15:09

Andrey