Tuesday, 28 November 2023

Revisit "Simple tab navigation using jQuery" using Vue.js

This is the first of a series in which I revisit old blog posts which made use of JavaScript and jQuery. I attempt to implement them, this time using Vue.js in order to improve my Vue.js skills.
First up is one from 2010 titled Simple tab navigation using jQuery.

index.html
<html lang="en">
  <head>
    <meta charset="UTF-8"></meta>
    <title>Tabbed Navigation</title>
    <style type="text/css">
      body {
        font-family: Sans-serif;
      }
      #subSystem {
        margin: 0 auto;
        width: 400px;
      }
      #subNav a.subMenu {
        display: block;
        text-decoration: none;
        float: left;
        text-align: center;
        width: 5rem;
        height: 2.5rem;
        padding-top: 1rem;
        border-top: 0.0625rem solid #ccc;
        border-left: 0.0625rem solid #ccc;
        border-right: 0.0625rem solid #ccc;
        color: #000;
      }
      #subNav a.subMenu:hover {
        background: #a3a3a3;
        color: #fff;
      }
      .menuSelected {
        background: #ccc;
        color: #fff;
      }
      #subContent {
        clear: left;
        min-height: 25rem;
        height: 25rem;
        border: 0.0625rem solid #ccc;
      }
    </style>
  </head>
  <body>
    <div id="subSystem">
      <div id="subNav">
        <a class="subMenu menuSelected" click="loadContent" href="./subPage1.html">First</a>
        <a class="subMenu" click="loadContent" href="./subPage2.html">Second</a>
        <a class="subMenu" click="loadContent" href="./subPage3.html">Third</a>
      </div>
      <div id="subContent"></div>
    </div>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
    <script src="./app.js"></script>
  </body>
</html>

app.js

const app = Vue.createApp({
  methods: {
    loadContent(event) {
      event.preventDefault();
      const href = event.target.getAttribute("href");
      fetch(href)
        .then((response) => response.text())
        .then((data) => {
          document.getElementById("subContent").innerHTML = data;
        })
        .catch((error) => {
          console.error("Error loading content:", error);
        });
    },
  },
  mounted() {
    // Simulate a click on the first tab when the page loads
    const firstTab = document.querySelector(".subMenu.menuSelected");
    if (firstTab) {
      firstTab.click();
    }
  },
});

app.mount("#subSystem");

No comments:

Post a Comment