Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Vue 3 Guide: Importing External Dependencies, Custom Components, and Routing

Tech 1

Important Note: The source code used in this article builds upon basic Vue 3 framework concepts, template syntax, and directives. Please ensure you are familiar with these fundamentals before proceeding.

1 Importing External Dependencies

Vue leverages Node.js to import external dependencies, allowing developers to utilize open-source libraries worldwide. This significantly reduces development difficulty and accelerates the building process.

1.1 Installing Element Plus

In this section, we will integrate Element Plus as an example. Element Plus is a powerful component library based on Vue 3, providing developers and designers with rich design resources and UI components to help websites rapidly take shape.

1.1.1 Updating main.js

While not strictly mandatory, registering Element Plus globally in main.js allows you to use its excellent components and styles throughout your entire application without importing them individually in each file. You can overwrite your existing main.js with the following content:

import { createApp } from 'vue';
import ElementPlus from 'element-plus';
import 'element-plus/dist/index.css';
import RootApp from './App.vue';

const vueApp = createApp(RootApp);

vueApp.use(ElementPlus);
vueApp.mount('#root');

1.1.2 Installation

Execute the installation command in your terminal:

npm install element-plus

Upon successful installation, you will see the corresponding succsess logs in your terminal.

1.1.3 Verification

Replace the button content in your Index.vue file with an Element Plus button component:

<el-button type="danger" @click="handleAction()">Click Me</el-button>

Refresh your page, and you will notice the button has adopted the Element Plus styling. Feel free to change the type attribute to warning, primary, etc., to observe different visual effects.

1.2 Installing Axios

Axios is an excellent tool for handling network requests.

1.2.1 Installation

npm install axios

1.2.2 Importing Axios

import httpClient from 'axios';

1.2.3 Making Requests

We will use a public API endpoint to test our network request:

const apiEndpoint = "https://placeholder.typicode.com/users/1";
httpClient.get(apiEndpoint).then(response => {
    console.log(response.data);
});

If you open your browser's developer console and see the JSON response logged, the request was successful.

1.2.4 Complete Index.vue Source Code

<template>
    <div>
        Hello World!
        {{ greetingText }}
        <el-button type="primary" @click="handleButtonClick()">Submit</el-button>
    </div>
</template>

<script>
    import httpClient from 'axios';
    import { defineComponent } from "vue";

    export default defineComponent({
        // Lifecycle hook, similar to onLoad
        mounted() {
            console.log("Index component initialized.");
        },
        // State management
        data() {
            return {
                greetingText: "Welcome"
            }
        },
        // Methods
        methods: {
            handleButtonClick() {
                this.greetingText = "Goodbye";

                // Making the network request
                const apiEndpoint = "https://placeholder.typicode.com/users/1";
                httpClient.get(apiEndpoint).then(response => {
                    console.log(response.data);
                });
            }
        }
    })
</script>

<style scoped>
</style>

2 Creating Custom Components

Here, we will create a custom user profile card component for demonstration. This card will display the user's name, email, and avatar.

2.1 Creating UserCard.vue in the Components Directory

Create a new file named UserCard.vue inside the components folder. Set up the standard template, script, and style tags. The following boilerplate can be reused for creating new pages or components:

<template>
    <div>
        
    </div>
</template>

<script>
    import { defineComponent } from "vue";

    export default defineComponent({
        mounted() {
            console.log("ProfileCard component loaded.");
        },
        data() {
            return {
                
            }
        },
        methods: {
        },
        props: []
    })
</script>

<style scoped>
</style>

2.2 Implementing UserCard.vue

Using HTML and CSS knowledge, we build the user interface for the profile card:

<template>
    <div style="text-align: center; margin-left: 25%;">
        <div class="card-container">
            <el-image
                style="width: 48px; height: 48px; border-radius: 50%;"
                :src="profileData.avatar"
                :fit="imageFit">
            </el-image>
            <div><el-text class="mx-1" type="success">{{ profileData.fullName }}</el-text></div>
            <div><el-text class="mx-1" type="warning">{{ profileData.email }}</el-text></div>
            <div><el-text class="mx-1" type="primary">{{ externalMessage }}</el-text></div>
        </div>
    </div>
</template>

<script>
    import { defineComponent } from "vue";

    export default defineComponent({
        mounted() {
            console.log("ProfileCard component loaded.");
        },
        data() {
            return {
                profileData: {
                    fullName: "John Doe",
                    email: "john.doe@example.com",
                    avatar: "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif?imageView2/1/w/80/h/80"
                },
                imageFit: 'cover'
            }
        },
        methods: {
        },
        props: [
            'externalMessage'
        ]
    })
</script>

<style scoped>
    .card-container {
        border: 15px solid lightcyan;
        padding: 24px;
        color: black;
        line-height: 42px;
        width: 50%;
        text-align: center;
    }
</style>

2.3 Integrating the Component in Index.vue

Import the newly created component into your main view. Pay close attention to the comments regarding component integration:

<template>
    <div>
        <!-- Component usage -->
        <ProfileCard externalMessage="Message from parent"></ProfileCard>
        Hello World!
        {{ greetingText }}
        <el-button type="primary" @click="handleButtonClick()">Submit</el-button>
    </div>
</template>

<script>
    import httpClient from 'axios';
    import { defineComponent } from "vue";
    
    // Importing the component
    import ProfileCard from '../components/UserCard.vue';

    export default defineComponent({
        // Registering the component
        components: {
            ProfileCard
        },
        mounted() {
            console.log("Index component initialized.");
        },
        data() {
            return {
                greetingText: "Welcome"
            }
        },
        methods: {
            handleButtonClick() {
                this.greetingText = "Goodbye";

                const apiEndpoint = "https://placeholder.typicode.com/users/1";
                httpClient.get(apiEndpoint).then(response => {
                    console.log(response.data);
                });
            }
        }
    })
</script>

<style scoped>
</style>

2.4 Execution Result

The rendered page should display the profile card as intended.

2.5 Passing Props to Components

As demonstrated in the code above, components can receive external data via props (e.g., the externalMessage prop).

3 Configuring Routing

3.1 Installing the Router Dependency

npm install vue-router

3.2 Creating a Login Page

Create a new file at views/login/Index.vue and implement a basic login layout.

3.3 Updating App.vue

Instead of hardcoding content directly in App.vue, replace it with the <RouterView> component to render views based on the current route:

<script setup>
import { RouterView } from 'vue-router'
</script>

<template>
  <RouterView />
</template>

<style scoped>
</style>

3.4 Updating main.js

Register the router instance with your Vue application:

// Register the router plugin
vueApp.use(router);

3.5 Defining Router Configuration

Create a router folder at the same level as the views directory, and inside it, create an index.js file:

import { createRouter, createWebHistory } from "vue-router";
import HomeView from '../views/Index.vue';

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    // Define your route paths and corresponding components here
    routes: [
        {
            path: '/',
            name: 'home',
            component: HomeView,
        },
        {
            path: '/login',
            name: 'login',
            component: () => import('../views/login/Index.vue')
        },
    ]
});

export default router;

3.6 Execution Result

Start your development server and navigate to the login route (note that your port number might vary):

http://localhost:5173/login

The corresponding login page component should now be rendered successfully.

4 Conclusion

Even for experienced developers, getting all these configurations and integrations working together smoothly can be challenging. Keep practicing and experimenting!

Tags: Vue 3

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.