如图,项目中用了vue-router放在图中路径下
/router/index.js中引入Vue及vue-router
import Vue from 'vue'
import Router from 'vue-router'
在main.js中有定义一个Vue.prototype.debug = true
现在想知道如何在/router/index.js中访问到Vue.prototype.debug这个对象?
如图,项目中用了vue-router放在图中路径下
/router/index.js中引入Vue及vue-router
import Vue from 'vue'
import Router from 'vue-router'
在main.js中有定义一个Vue.prototype.debug = true
现在想知道如何在/router/index.js中访问到Vue.prototype.debug这个对象?
我去试了下
main.js
Vue.prototype.debug = true// 往vue的原型上添加方法
router.js
alert(this.debug)// 在路由.js文件里,任意位置alert 都是undefined
然后试了下在单文件组件里 .vue 是可以的
XX.vue
created () {
alert(this.debug)
}
题主的本意是不是想,判断不同的路由页面,动态改变this.debug的true和false?
如果是这样的话,可以在父组件(一般是App.vue)写一个watch 监听路由。
watch:{
'$route': 'fn'
},
methods () {
fn () {
if(this.$route.name==='index'){
this.debug=true/false
}else {
...
}
}
}
访问不到的原因是代码执行的顺序问题,/router/index.js执行的时候main.js中的这句代码(Vue.prototype.debug = true)还没有执行。
13 回答12.9k 阅读
7 回答2.1k 阅读
9 回答1.7k 阅读✓ 已解决
6 回答1.5k 阅读
3 回答1.3k 阅读✓ 已解决
3 回答1.4k 阅读✓ 已解决
2 回答1.3k 阅读✓ 已解决
你的问题我也不知道怎么处理。
我的曲线救国的方法是:定义一个config.js,在里面声明
export const APP_DEBUG_MODE = true
,然后在你的需要判断Vue.debug的地方引入这个config来判断APP_DEBUG_MODE的值