2016-11-14 374 views
1

我是vuejs的初学者。 我在单个文件.vue上创建了我的第一个vuejs组件。

我想获得路线的参数。但是“这个”没有$路线。这是Window。有人可以帮我理解吗?

在main.js,我配置了路由器:

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>' 
}); 

在songbook.vue,在这里我希望在这个使用用户id $ route.params,我有:

<template> 
<div> 
    <h1>Songbook</h1> 
</div> 
</template> 

<script> 

var getPlaylists = function() { 
    console.log(this); 
}; 

getPlaylists(); 

module.exports = { 
    data: function() { 
     return { 
     } 
    } 
} 
</script> 

console.log(this)给了我窗口对象,而不是带有$ route的对象。我看不出问题在哪里...... SOS :-)

此致敬意。

回答

1

在这种情况下,getPlaylist函数只是一个常规函数,不会绑定到this关键字。尽管第一眼看起来可能与直觉相反,但Vue只能将组件的上下文绑定到导出的配置对象(module.exports = { ... })中的方法,因此this将可用。在data函数内但不在getPlaylist

如果你真的需要在功能this的配置对象之外,你必须做这样的事情:

<script> 
    var getPlaylists = function() { 
     console.log(this); 
    }; 

    module.exports = { 
     data: function() { 
      getPlaylists.call(this); // supply context to getPlaylists() 
      return { }; 
     } 
    } 
</script> 
+0

谢谢! C'estcomplètementlogique。 – Manu

+0

@Manu如果能解决你的问题,你能接受我的答案吗? – Aletheios