如何使用 Vue.js 判斷年份是閏年還是平年?
Vue.js 可以定義為一個用於構建使用者介面的漸進式框架。它有多個指令,可以根據使用者的需求使用。其核心庫主要專注於構建檢視層,並且易於選擇其他庫或與之整合。
在本文中,我們將使用 Vue 過濾器來檢查字串是否為閏年。閏年有 366 天,而平年只有 365 天。我們可以使用邏輯來檢查年份是否為閏年。如果年份能被 400 或 4 整除,則為閏年,否則為平年。
if (year % 100 === 0) { if (year % 400 === 0) { return "Leapyear"; } else { return "Non-Leapyear"; } } else { if (year % 4 === 0) { return "Leapyear"; } else { return "Non-Leapyear"; } }
步驟
我們可以按照以下步驟將年份分類為閏年或平年:
定義一個名為 leapyear 的函式,該函式接受一個年份引數。
使用模運算子 (%) 檢查年份是否能被 100 整除,以獲取年份除以 100 的餘數。如果餘數為 0,則表示年份能被 100 整除。
如果年份能被 100 整除,則檢查它是否也能被 400 整除。如果年份除以 400 的餘數為 0,則表示該年份為閏年。在這種情況下,返回字串 "Leapyear"。
如果年份能被 100 整除但不能被 400 整除,則它不是閏年。在這種情況下,返回字串 "Non-Leapyear"。
如果年份不能被 100 整除,如果它能被 4 整除,它仍然可能是閏年。檢查年份除以 4 的餘數是否為 0。如果是,則該年份為閏年。在這種情況下,返回字串 "Leapyear"。
如果年份不能被 100 整除也不能被 4 整除,則它不是閏年。在這種情況下,返回字串 "Non-Leapyear"。
示例:檢查年份是否為閏年
首先,我們需要建立一個 Vue 專案。為此,您可以參考此頁面。在您的 Vue 專案中建立兩個檔案 app.js 和 index.html。下面給出了這兩個檔案的程式碼片段及其檔案和目錄結構。將下面的程式碼片段複製並貼上到您的 Vue 專案中,然後執行 Vue 專案。您將在瀏覽器視窗中看到以下輸出。
檔名 - app.js
目錄結構 -- $project/public -- app.js
// Defining the years & checking if its leap or not const parent = new Vue({ el: "#parent", data: { year1: 2021, year2: 1996, year3: 1900, year4: 2000, year5: 1997, }, filters: { leapyear: function (year) { if (year % 100 === 0) { if (year % 400 === 0) { return "Leapyear"; } else { return "Non-Leapyear"; } } else { if (year % 4 === 0) { return "Leapyear"; } else { return "Non-Leapyear"; } } }, }, });
檔名 - index.html
目錄結構 -- $project/public -- index.html
<html> <head> <script src= "https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div id='parent'> <!-- Checking if an year is leap or not --> <p><strong>{{year1}} : </strong> {{ year1 | leapyear }} </p> <p><strong>{{year2}} : </strong> {{ year2 | leapyear }} </p> <p><strong>{{year3}} : </strong> {{ year3 | leapyear }} </p> <p><strong>{{year4}} : </strong> {{ year4 | leapyear }} </p> <p><strong>{{year5}} : </strong> {{ year5 | leapyear }} </p> </div> <script src='app.js'></script> </body> </html>
執行以下命令以獲得以下輸出:
C://my-project/ > npm run serve
完整程式碼
<html> <head> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div id='parent'> <p><strong>{{year1}} : </strong> {{ year1 | leapyear }} </p> <p><strong>{{year2}} : </strong> {{ year2 | leapyear }} </p> <p><strong>{{year3}} : </strong> {{ year3 | leapyear }} </p> <p><strong>{{year4}} : </strong> {{ year4 | leapyear }} </p> <p><strong>{{year5}} : </strong> {{ year5 | leapyear }} </p> </div> <script> // Defining the years & checking if its leap or not const parent = new Vue({ el: "#parent", data: {year1: 2021, year2: 1996, year3: 1900, year4: 2000, year5: 1997,}, filters: { leapyear: function(year) { if (year % 100 === 0) { if (year % 400 === 0) { return "Leapyear"; } else { return "Non-Leapyear"; } } else { if (year % 4 === 0) { return "Leapyear"; } else { return "Non-Leapyear"; } } }, }, }); </script> </body> </html>
在上面的示例中,我們檢查了五年,並顯示特定年份是閏年還是平年。