【问题标题】:Vue.js - Initialise a variable on page loadVue.js - 在页面加载时初始化变量
【发布时间】:2020-10-11 10:38:55
【问题描述】:

我目前正在使用 Vue.js 和 JavaScript 开发一个 webapp,并且出于性能原因正在整合 .js 文件。在合并 .js 文件之前,我为每个静态 html 页面创建了一个单独的 .js 文件。在每个 .js 文件中都有一个名为 initialise() 的方法,该方法在创建的钩子上调用,该钩子调用其他初始化相关变量的初始化方法。但是现在我已经合并了 .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();
    }
}

还有一个名为 currentPage 的 vue 变量,我尝试在页面加载时在 html 正文标记中对其进行初始化,例如 <body v-on:load="currentPage='profile'">

v-on:load 但是,似乎不起作用。有没有办法根据当前页面初始化一个vue变量?

【问题讨论】:

  • 你在应用中使用过 Vue Router 吗?我认为这是一个更好的选择。
  • 查看此页面的生命周期挂钩部分...vuejs.org/v2/guide/instance.html
  • 是的,我已经用创建的钩子调用了initialise(),我只需要初始化特定于用户当前所在的页面

标签: javascript html vue.js


【解决方案1】:

我想通了。使用创建的钩子,我还用window.location.pathname 初始化了currentPage,它初始化了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();
    }
}

这会根据页面调用正确的初始化方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-12-14
    • 2018-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多