How do you create a page in Vue?
sobes.tech AI
Answer from AI
A Vue page is usually created as a separate component (.vue file), which consists of three sections: <template>, <script>, and <style>.
-
<template>: Defines the HTML structure of the page, using Vue template syntax for data binding and logic.<template> <div> <h1>{{ pageTitle }}</h1> <p>{{ pageContent }}</p> </div> </template> -
<script>: Contains the JavaScript logic of the page, including data (data), computed properties (computed), methods (methods), lifecycle hooks, and other component options.<script> export default { data() { return { pageTitle: 'My Vue Page', pageContent: 'This is the content of my first Vue page.' }; }, mounted() { // Logic executed after the component is mounted console.log('Page mounted!'); } } </script> -
<style>: Contains CSS styles applied to the component. You can use thescopedmodifier to restrict the style scope to this component only.<style scoped> h1 { color: blue; } p { font-size: 16px; } </style>
The created component is then imported into the routing file (for example, using vue-router) and linked to a specific URL address, which allows this page to be displayed when navigating to that address.
// router/index.js (example with vue-router)
import { createRouter, createWebHistory } from 'vue-router';
import MyPage from '@/views/MyPage.vue'; // Import the page component
const routes = [
{
path: '/my-page', // URL address of the page
name: 'MyPage',
component: MyPage // Component to be displayed
}
];
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes
});
export default router;
In the main application file (main.js), the router is connected to the Vue app instance.
// main.js
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
createApp(App).use(router).mount('#app');
Thus, creating a page in Vue boils down to creating a component that describes its structure, logic, and styles, and then configuring the router to display this component at a specific URL.