sud*_*udo 6 javascript vue.js vue-router vuejs2
我未定义
这一点.$路由器
在App.vue和其他组件中未定义.我找不到解决方案.
这是我的main.js的一部分
Vue.use(VueRouter);
Vue.use(VueResource);
const router = new VueRouter({
routes: Routes,
mode: 'history'
});
new Vue({
el: '#app',
render: h => h(App),
router
});
Run Code Online (Sandbox Code Playgroud)
在这里我的router.js我正在主js导入.
export default [
{path: '/', component: Home, name: 'home'},
{path: '/home', component: Home, name: 'home2'},
{path: '/user/login', component: Login, name: 'userLogin'}
];
Run Code Online (Sandbox Code Playgroud)
谢谢 :)
我在这样的脚本标签中使用,
<script>
import HeadNavBar from './components/HeadNavBar.vue';
import SideBarNav from './components/SideBarNav.vue';
import Home from './components/Home.vue';
console.log(this.$router,pus); //the undefined type
export default {
name: 'app',
data() {
return {
isLogin: true
}
},
components: {
'app-headnav': HeadNavBar,
'app-sidebarnav': SideBarNav,
'app-home': Home
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
但当我改变它使用在methos标签内我得到了响应我在等待.
export default {
name: 'app',
data() {
return {
isLogin: true
}
},
components: {
'app-headnav': HeadNavBar,
'app-sidebarnav': SideBarNav,
'app-home': Home
},methods: {
myFunc: function() {
console.log(this.$router,pus); // this gave result
}
}
}
Run Code Online (Sandbox Code Playgroud)
我只能在使用箭头功能时重现undefined错误(也许这就是你正在做的事情),这是Vue文档建议的:this.$router
不要在选项属性或回调上使用箭头函数,例如
created: () => console.log(this.a)或vm.$watch('a', newValue => this.myMethod()).由于箭头函数绑定到父上下文,this因此不会像您期望的那样成为Vue实例,通常会导致诸如Uncaught TypeError: Cannot read property of undefined或之类的错误Uncaught TypeError: this.myMethod is not a function.
以下是成功mounted回调日志记录的示例this.$router:
<script>
export default {
name: 'app',
// DON'T USE ARROW FUNCTIONS HERE
// mounted: () => {
// console.log({router: this.$router});
// },
mounted() {
console.log({router: this.$router});
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
小智 6
我知道这已经过时了,但我会分享我遇到的一些事情以及我如何解决它,以防有人在那里苦苦挣扎。
我的场景是 vue/meteor 项目。
在函数/处理程序中,“this”指的是函数的目标,因此 this.$router 正在函数内或目标本身中查找 $router。
///////DOESN'T WORK ///////////
mounted: function () {
$(document).on('click', '.element', function(){
//this is recognized as
this.$router.push(PATH)
});
},
////////THIS WORKS//////////
mounted: function () {
//make router defined outside of function.
var navigate = this.$router;
$(document).on('click', '.element', function(){
navigate.push(PATH)
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10920 次 |
| 最近记录: |