Monday, December 9, 2024

MAD2-Viva5

 Component Basics: Explanation of any  one of the vue.js component ?

export default {}
This exports the Vue component definition as the default export, making it reusable in other parts of the application

name: "MyServices",

The component's name is MyServices, helpful for debugging tools and readability.

data() { return { myServices: [] }; }

  • data(): A function returning the reactive state of the component.
  • myServices: An array initialized as empty, meant to store a list of service requests fetched from the API.
methods: {}
The methods property contains functions for handling logic and user interactions.The below function is defined in methods

async fetchMyServices() {}

  • Declares an asynchronous function to fetch services data from the backend.

try { const response = await fetch('/api/my-services', 

  { headers: { 

       'Content-Type': 'application/json', 

       'Authentication-Token': localStorage.getItem('auth-token'),

    }, 

   }); 

}

  • fetch('/api/my-services'): Sends an HTTP request to the API endpoint to retrieve services.
  • headers: Specifies HTTP headers for the request.
    • Content-Type: Tells the server the format of the data being sent.
    • Authentication-Token: Retrieves the user's authentication token from localStorage to include in the request.

if (!response.ok) {}

  • Checks if the response indicates a successful HTTP status (e.g., 200 OK). If not, it logs an error and throws error

const data = await response.json();

  • Parses the API's response into a JavaScript object or array.
  • if (Array.isArray(data)) { this.myServices = data; } else {}

    • Verifies the response is an array (expected format). If not, logs an error and sets myServices to an empty list.
  • catch (error) {}

    • Handles any errors encountered during the API call or parsing.
    created() { this.fetchMyServices(); }
    • The created lifecycle hook is called after the component is initialized. It triggers the fetchMyServices method to load data when the component is created.
  • <table v-if="myServices.length > 0">

    • Shows a table of services if myServices is not empty.
  • v-for="service in myServices" :key="service.id"

    • Loops over the myServices array to render a table row for each service. The :key binds a unique identifier for optimization.

    Summary:

    • This Vue component fetches service requests, displays them in a table, and allows updating their status.
    • It integrates with a backend API for data fetching and updates.
    • Lifecycle hooks and reactivity ensure the data is loaded and displayed dynamically.
    Difference between Vue CLI and CDN?
    CDN:
    To use Vue.js via a CDN (Content Delivery Network), you can embed vue  and router cdn links   in a <script> tag in your HTML file. Vue provides CDN links for both development and production versions,used for smaller projects.
    CLI:
    The Vue CLI is a command-line interface tool that simplifies the process of creating and managing Vue.js applications.It generates a project structure with tools like vue router,Vuex , webpacks and hot module replacement(HMR)

    Single Page Applications (SPAs)

    An SPA is a web application that dynamically updates the content on a single HTML(index.html) page rather than loading new pages from the server for each interaction. Vue CLI ,vue router helps build SPAs 

    1. Dynamic Content Loading:

      • With Vue Router, different views (or pages) load dynamically based on the URL, but the page itself never reloads.
      • Faster navigation between pages since only necessary content is updated, not the entire page.

    Vue Router?

    • What it does: Manages navigation and views in your SPA (Single Page Application). Allows you to create multi-view apps without reloading the page. Each route is linked to a component (like "Home").
    • Example: Clicking a "Home" button in your SPA dynamically loads the home component without refreshing the browser.

    Complete Project Structure

    When you create a Vue project using the Vue CLI, it automatically sets up a directory structure that is ready for development and deployment. The structure includes:

    1. Source Files (src):
      • main.js: Entry point for your application.
      • App.vue: Root Vue component.
      • components/: A directory for Vue components.
    2. Configuration Files:
      • package.json: Manages dependencies and scripts.
      • babel.config.js: Configures Babel for modern JavaScript features.
      • vue.config.js (optional): Customizes build configuration.
    3. Public Folder (public):
      • Contains static assets like index.html for your app's entry point.
    VUE CLI Integrate the tools :
    1. Hot Reloading:

      •  Automatically updates the browser when you save changes in your code.
      • You can see updates instantly without manually refreshing the page, making development faster and more interactive.
      • Example: Edit a component, save it, and the changes appear in the browser immediately.
    2. Webpack:

      •  A module bundler that compiles your Vue files, JavaScript, CSS, and other assets into optimized bundles.
      •  Ensures your app runs efficiently in production by reducing file size and  Supports code splitting, lazy loading, and asset optimization.
    3. Vue Router:Is a library used to handle the navigation with in a SPA's .It allows you to map a specic URL to component,i.e navigation of different views of app with out reloading the page.It is array of objects .Each object represents a route with properties like path, component

    Explain the router.js ?
    The routes array defines the mapping between URLs (paths) and the components to be displayed when those URLs are accessed
    EX:
    const routes = [
        { path: "/", component: Home, name: "Home" },
        { path: "/user-login", component: Login, name: "Login" },
        
    ];

    Key Points about Routes:

    • path: The URL path a user navigates to.
    • component: The Vue component to render for that path.
    • name: A unique name for the route, used for navigation (e.g., router.push({ name: "Home" })).

    Vue Router Instance?

    A new VueRouter instance is created with the routes array, This instance manages the routing for your application.

    const router = new VueRouter({
        routes,
    });

    Navigation Guards?

    The router.beforeEach() method sets up a global navigation guard that runs before every route change. It controls access to routes based on authentication and user roles:

    The beforeEach navigation guard ensures:

    • Logged-in users cannot access login/register pages.
    • Non-logged-in users are redirected to the login pages for all other routes.
    router.beforeEach((to, from, next) => {
        let isLoggedIn = localStorage.getItem("auth-token");
        let role = localStorage.getItem("role");  // Fetch role from localStorage
        const loginPages = ["CustomerRegister", "ProfessionalRegister", "Login"];

    If the user is navigating to a login-related page (e.g., "CustomerRegister", "ProfessionalRegister", "Login") and is already logged in (isLoggedIn exists), they are redirected to the Home page:

    if (loginPages.includes(to.name)) {
        if (isLoggedIn) {
            next({ name: "Home" });
        } else {
            next();
        }
    }
    with app.app_context() explain?

    with app.app_context() is a context manager in Flask that allows you to temporarily activate
    the application context of a Flask app. This is particularly useful when working with Flask features
    that require an application context, such as interacting with the configuration, accessing database
    models, or running Flask commands outside of a request context.

    Flask operates in different contexts: application context and request context.
    Some operations,such as querying a database or accessing app configuration, require the application context to be active.
    By default, this context is active only during an HTTP request.

    what is <router-view>?

    1.<router-view> is a Vue Router component used in Vue.js applications to dynamically display components
    based on the current route. It acts as a placeholder where the matched component for a given route will be rendered
    2.<router-view> is essential in Vue Router-based applications, acting as the dynamic container
    for route components and enabling the entire routing flow.

    what is <router-link>?
    <router-link> is a built-in component provided by Vue Router in Vue.js that is used to create navigation links within a Vue application. It enables users to navigate between different routes defined in your app without reloading the page, client-side routing

    <router-link to="/about">About</router-link>
    Declarative Navigation: Allows you to define navigation links easily with the to attribute.
  • The to attribute specifies the route to navigate to.
  • When clicked:
    • The browser's URL updates ( /about).
    • The corresponding route's component is rendered in <router-view>.
  • What is a Route?

    A Route maps a URL(uniform resource locator) path to a component
    What is WSGI?(web Server Gateway Interface)
    Is an Interface between the web server and web application.It is a python specification .
    web server---->send requests to the WSGI ----->forward the request to web application
    web Application (process the request)-------> send responses to WSGI--->send responses to web server

    WSGI is Synchronous ,may not handle asynchronous apps
    ASGI is Asynchronous Server Gate way Interface 
    Event:
    Events in Vue are actions or occurrences triggered by the user (e.g., clicking a button, typing in an input field) or the application itself (e.g., a component lifecycle event). Vue provides a way to handle these events using its event handling system
    Button clicking an event --loading or rendering  of html template 

    In Vue, when a button is clicked, you can use a method to trigger an action, such as rendering a template .In the backend, send an API request to the Flask backend to render the required HTML template or fetch data.









    No comments:

    Post a Comment

    Mangerial Economics Quiz1 solutions Guide

    Mangerial Economics Quiz1 solutions Guide  solutions watch on you tube channel