Reputation: 25
I'm beginner with vuejs. I started my first vuejs component on a single file .vue.
I wanted to get the param of a route. But "this" doesn't have $route. this is Window. Somebody can help me to understand ?
In main.js, I configured the router with :
var Vue = require('vue');
var VueRouter = require('vue-router');
Vue.use(VueRouter);
const Home = require('./components/home.vue');
const Songbook = require('./components/songbook.vue');
var router = new VueRouter({
routes: [{
path: '/',
component: Home
}, {
path: '/songbook/:userId',
component: Songbook
}]
});
const app = new Vue({
router: router,
el : '#app',
template : '<router-view></router-view>'
});
In songbook.vue, where I hope use userId on this.$route.params, I have :
<template>
<div>
<h1>Songbook</h1>
</div>
</template>
<script>
var getPlaylists = function() {
console.log(this);
};
getPlaylists();
module.exports = {
data: function() {
return {
}
}
}
</script>
The console.log(this) give me the window object, not an object with $route. I don't see where is the problem... SOS :-)
Best regards.
Upvotes: 1
Views: 445
Reputation: 4020
In this case the getPlaylist
function is just a regular function and not bound to the this
keyword. Even though it might be counter-intuitive at first glance, Vue can only bind the component's context to methods in the exported config object (module.exports = { ... }
), so this
will be available e.g. inside the data
function but not in getPlaylist
.
If you really need this
in functions outside of the config object, you'll have to do something like this:
<script>
var getPlaylists = function() {
console.log(this);
};
module.exports = {
data: function() {
getPlaylists.call(this); // supply context to getPlaylists()
return { };
}
}
</script>
Upvotes: 1