Vue.js中mounted钩子调用hideMe函数失效,求排查原因
问题排查与解决
首先一眼就发现了最直接的问题——方法名大小写不匹配!你在methods里定义的是驼峰式的hideMe()(M大写),但在mounted钩子中调用的却是this.hideme()(m小写)。JavaScript是严格区分大小写的语言,这就导致代码找不到对应的方法,自然不会执行啦。
修复步骤
- 先修正mounted里的调用语句,改成正确的驼峰写法:
mounted() { this.hideMe(); // 把hideme改成hideMe console.log("This is a breakpoint name " + this.$vuetify.breakpoint.name); }
- 另外,你的
console.log里还有个小坑:
console.log("When is this rendered? " + this.$vuetify.breakpoint.name == 'xs');
这里+的优先级比==高,会先把字符串和断点名称拼接,再和'xs'做比较,最终输出的只会是true或false,不是你想要的“显示断点名称+判断结果”的效果。可以改成两种写法:
// 模板字符串更直观 console.log(`When is this rendered? ${this.$vuetify.breakpoint.name === 'xs'}`); // 或者用括号包裹判断逻辑 console.log("When is this rendered? " + (this.$vuetify.breakpoint.name == 'xs'));
- 额外检查:确保你已经正确引入并初始化了Vuetify,只有Vuetify配置到位,
this.$vuetify.breakpoint才能正常获取值。如果这个属性是undefined,函数里的判断逻辑也不会触发。
修复后的完整代码示例
export default { data() { return { show: "initial" } }, methods: { hideMe() { if(this.$vuetify.breakpoint.name === 'xs') { console.log(`When is this rendered? ${this.$vuetify.breakpoint.name === 'xs'}`); this.show = "none"; } } }, mounted() { this.hideMe(); console.log("This is a breakpoint name " + this.$vuetify.breakpoint.name); } }
内容的提问来源于stack exchange,提问作者ToddT
相关产品推荐
相关产品推荐

