Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Frontend Technical Concepts for Computer Science Project Defenses

Tech May 9 4

1. Overview of Vue.js

Vue.js is a progressive JavaScript framework designed for building user interfaces. It utilizes standard HTML, CSS, and JavaScript to offer a declarative and component-driven programming model. This approach allows developers to encapsulate the structure (HTML), styling (CSS), and logic (JS) of a specific part of the UI into a single .vue file. These components can represent basic elements, like a custom button, or entire pages, like a registration form. By breaking down complex applications into reusable components, Vue.js significantly enhances development efficiency and maintainability.

2. Standard Vue Project Structure

package.json

This file serves as the project manifest. It contains metadata about the project and defines scripts for starting or building the application. Most importantly, it lists the dependencies required for the project to run.

When cloning a repository, running npm install reads this file to download the necessary modules into the node_modules folder. Key fields include:

  • name: The project identifier. It must be lowercase and less than 215 characters.
  • version: The current version of the project, following semantic versioning.

package-lock.json

Generated automaticalyl during npm install, this file locks the dependency tree. It records the exact version and download source of every installed package. This ensures that when the project is installed on another machine, the dependencies match exactly, preventing version conflicts and speeding up the installation process.

main.js

This is the entry point of the application. It initializes the Vue instance and mounts it to the DOM, typically targeting a specific element like <div id="app">.

3. Essential NPM Commands

  • npm install: Scans package.json and downloads all required dependencies into the node_modules directory.
  • npm run <script-name>: Executes a custom script defined in the scripts section of package.json (e.g., npm run serve or npm run build).

4. Understanding Sessions

A Session represents a server-side storage mechanism used to maintain state between HTTP requests. Since HTTP is stateless, a Session allows the server to remember a specific client (user) across multiple requests during a browsing period. The server creates the session and stores data (like user ID or preferences), often identified by a Session ID passed via cookies.

5. Differences Between GET and POST

The primary distinctions lie in their purpose and data transmission methods:

  • Semantics: GET is designed for retrieving data without causing side effects. POST is designed for submitting data to be processed, often resulting in a change on the server (like creating a record).
  • Data Location: GET parameters are appended to the URL (e.g., ?id=123), making them visible. POST parameters are sent within the request body, keeping them hidden from the URL bar.

Implementation Example:

// Fetching data using GET (Params in URL)
const fetchUser = {
  userId: 101,
  role: 'admin'
}

axios.get('http://localhost:3000/api/user/profile', {
  params: fetchUser
}).then(response => {
  console.log('User Data:', response.data)
})

// Submitting data using POST (Data in Body)
const newProfile = {
  username: 'developer_jane',
  email: 'jane@example.com'
}

axios.post('http://localhost:3000/api/user/create', newProfile)
  .then(response => {
    console.log('Creation Status:', response.data)
  })

6. Data Exchange Between Frontend and Backend

Modern applications typically use AJAX requests. In a Vue environment, axios is the standard library for this purpose.

Configuring the HTTP Client:

import axios from 'axios'
import store from '@/store' // Assuming a Vuex store for state management

const apiClient = axios.create({
  baseURL: '/api/v1',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// Interceptor to attach Authorization Token
apiClient.interceptors.request.use(config => {
  const token = store.state.auth.token
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }
  return config
})

// Interceptor to handle global errors (e.g., 401 Unauthorized)
apiClient.interceptors.response.use(
  response => response,
  error => {
    if (error.response && error.response.status === 401) {
      console.error('Session expired. Please login again.')
      // Logic to redirect to login
    }
    return Promise.reject(error)
  }
)

export default apiClient

Consuming the API: The frontend calls the backend endpoint. The backend Controller receives request, delegates logic to the Service layer, interacts with the Database via the Mapper/Persistence layer, and returns the result (usually JSON) back to the frontend for rendering.

this.$http.post('/account/update', this.formData)
  .then(({ data }) => {
    if (data.code === 200) {
      this.$notify({ type: 'success', message: 'Profile updated successfully' })
    }
  })

7. Routing Configuration

Vue Router manages navigation. The configuration maps URL paths to specific components.

import Vue from 'vue'
import VueRouter from 'vue-router'
import Dashboard from '@/views/Dashboard.vue'
import UserProfile from '@/views/UserProfile.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Dashboard',
    component: Dashboard
  },
  {
    path: '/user/:id',
    name: 'UserProfile',
    component: UserProfile,
    children: [
      { path: 'settings', component: () => import('@/views/UserSettings.vue') }
    ]
  }
]

export default new VueRouter({ mode: 'history', routes })

8. Imlpementing Breadcrumb Navigation

Breadcrumbs rely on route metadata (meta) to display hierarchical titles.

Route Definition:

{
  path: '/dashboard/settings',
  name: 'SettingsPage',
  component: Settings,
  meta: { title: 'Account Settings', breadcrumb: ['Dashboard', 'Settings'] }
}

Breadcrumb Logic: Watch the route object to dynamically generate the trail.

watch: {
  '$route' (to) {
    this.trail = to.matched.map(route => {
      return route.meta.breadcrumb ? route.meta.breadcrumb[route.meta.breadcrumb.length - 1] : route.name
    })
  }
}

Template Rendering:

<nav aria-label="breadcrumb">
  <ol class="breadcrumb">
    <li v-for="(crumb, index) in trail" :key="index" class="breadcrumb-item">
      <router-link v-if="index < trail.length - 1" :to="crumb.path">{{ crumb }}</router-link>
      <span v-else>{{ crumb }}</span>
    </li>
  </ol>
</nav>

9. Component Reusability

Components allow you to split the UI into independent, reusable pieces.

Parent Component Usage:

<script setup>
import AlertBox from './components/AlertBox.vue'
</script>

<template>
  <div class="app-container">
    <h1>Main Application</h1>
    <AlertBox message="Data saved successfully!" type="success" />
  </div>
</template>

Child Component (AlertBox.vue):

<template>
  <div :class="['alert', `alert-${type}`]">
    {{ message }}
  </div>
</template>

<script setup>
defineProps({
  message: String,
  type: {
    type: String,
    default: 'info'
  }
})
</script>

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.