javascript - Vue.js - 在页面加载时初始化变量
问题描述
我目前正在使用 Vue.js 和 JavaScript 开发一个 webapp,并且出于性能原因正在整合 .js 文件。在合并 .js 文件之前,我为每个静态 html 页面创建了一个单独的 .js 文件。在每个 .js 文件中都有一个名为 initialise() 的方法,该方法在 created 钩子上调用,该钩子调用其他初始化相关变量的初始化方法。但是现在我已经合并了 .js 文件,我需要某种方式来仅调用与当前页面相关的初始化方法。
我尝试这样做的一种方法是让我的 initialise() 方法如下:
initialise: function() {
if (this.currentPage=="profile") {
this.getNightmode();
this.getProfile();
this.getTaskTypes();
} else if (this.currentPage=="postRegistration") {
this.getSignUpMethod();
this.getAccountType();
this.getTaskTypes();
}
}
和一个调用的 vue 变量currentPage
,我尝试在页面加载时在 html body 标记中初始化,就像这样<body v-on:load="currentPage='profile'">
v-on:load
,但是,似乎不起作用。有没有办法根据当前页面初始化一个vue变量?
解决方案
我已经想通了。使用 created 钩子我也currentPage
用初始化window.location.pathname
,它初始化currentPage
当前的 URL 路径名。我的初始化方法现在看起来像
initialise: function() {
if (this.currentPage=="/profile.html") {
this.getNightmode();
this.getProfile();
this.getTaskTypes();
} else if (this.currentPage=="/post_registration.html") {
this.getSignUpMethod();
this.getAccountType();
this.getTaskTypes();
}
}
这会根据页面调用正确的初始化方法。