簡體   English   中英

Vue.js - 在頁面加載時初始化變量

[英]Vue.js - Initialise a variable on page load

我目前正在使用 Vue.js 和 JavaScript 開發一個 webapp,並且出於性能原因正在整合 .js 文件。 在合並 .js 文件之前,我為每個 static 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();
    }
}

還有一個名為currentPage的 vue 變量,我嘗試在頁面加載時在 html 正文標記中進行初始化,例如<body v-on:load="currentPage='profile'">

但是, v-on:load似乎不起作用。 有沒有辦法根據當前頁面初始化一個vue變量?

我已經想通了。 使用創建的鈎子,我還用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();
    }
}

這會根據頁面調用正確的初始化方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM