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.
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
}
]
})
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');
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With