Easy to useCreate a projectvue-cli create$npm install -g @vue/cli $vue --version @vue/cli 4.5.15 $vue create my-project Then the steps:
File structure: my-project +--- babel.config.js +--- package-lock.json +--- package.json +--- public | +--- favicon.ico | +--- index.html +--- README.md +--- src | +--- App.vue | +--- assets | | +--- logo.png | +--- components | | +--- HelloWorld.vue | +--- main.ts | +--- shims-vue.d.ts +--- tsconfig.json +--- node_modules | +--- ...
vite creationExecute the following command to create a project $npm init vite-app <project-name> $cd <project-name> $ npm install $ npm run dev File structure: project-name +--- index.html +--- package-lock.json +--- package.json +--- public | +--- favicon.ico +--- src | +--- App.vue | +--- assets | | +--- logo.png | +--- components | | +--- HelloWorld.vue | +--- index.css | +--- main.js +--- node_modules | +--- ...
Note: Since the project created using the vite method does not have a vue declaration file, we need to customize it, otherwise an error will be reported. /* eslint-disable */ declare module '*.vue' { import type { DefineComponent } from 'vue' const component: DefineComponent<{}, {}, any> export default component } Install vue-router$ npm install vue-router@4 At this point, { "name": "my-project", "version": "0.1.0", "private": true, "scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build", "lint": "vue-cli-service lint" }, "dependencies": { "core-js": "^3.6.5", "vue": "^3.0.0", "vue-router": "^4.0.12" }, "devDependencies": { "@typescript-eslint/eslint-plugin": "^4.18.0", "@typescript-eslint/parser": "^4.18.0", "@vue/cli-plugin-babel": "~4.5.0", "@vue/cli-plugin-eslint": "~4.5.0", "@vue/cli-plugin-typescript": "~4.5.0", "@vue/cli-service": "~4.5.0", "@vue/compiler-sfc": "^3.0.0", "@vue/eslint-config-typescript": "^7.0.0", "eslint": "^6.7.2", "eslint-plugin-vue": "^7.0.0", "typescript": "~4.1.5" } } Create/Modify Components Create import { createRouter, createWebHashHistory } from "vue-router" import Home from '../components/Home.vue' import About from '../components/About.vue' import User from '../components/User.vue' const routes = [ // See below for details of router parameters { path: "/home", name: "home", component: Home }, { path: "/about", name: "about", component: About }, { path: "/user/:uid", // dynamic parameter name: "user", component: User } ] export const router = createRouter({ history: createWebHashHistory(), routes: routes }) Create components: <template> <div>home component</div> </template> <script lang="ts"> import { defineComponent } from "vue"; export default defineComponent({ name: "Home", setup() { return { //Returned data }; }, }); </script> <template> <div>About component</div> </template> <script lang="ts"> import { defineComponent } from "vue"; export default defineComponent({ name: "About", setup() { return { //Returned data }; }, }); </script> <template> <div>User component</div> </template> <script lang="ts"> import { defineComponent } from "vue"; export default defineComponent({ name: "User", setup() { return { //Returned data }; }, }); </script> Modify <template> <div>{{ appMessage }}</div> <!-- router-link will be rendered as a tag--> <router-link to="/home">home</router-link> <router-link to="/about">about</router-link> <router-link to="/user/lczmx">user</router-link> <!-- Routing exit --> <!-- Components matched by the route will be rendered here--> <router-view></router-view> </template> <script lang="ts"> import { defineComponent } from "vue"; export default defineComponent({ name: "App", setup() { const appMessage = "App component"; return { //Returned data appMessage, }; }, }); </script> <style> /* Add styles */ #app { text-align: center; margin-top: 50px; } a { margin: 30px; display: inline-block; } </style> Modify the entry ts Modify import { createApp } from 'vue' import App from './App.vue' import './index.css' import { router } from './router' // Create an application and return the corresponding instance object const app = createApp(App) // Install vue-router plugin app.use(router) // Call the mount method app.mount('#app') Start Vue$ npm run serve > [email protected] serve > vue-cli-service serve INFO Starting development server... 98% after emitting CopyPlugin DONE Compiled successfully in 6387ms 4:14:30 PM App running at: - Local: http://localhost:8080/ - Network: http://192.168.43.12:8080/ Note that the development build is not optimized. To create a production build, run npm run build. No issues found. Access in browser According to the prompt, visit File structure pictureComprehensive UseDynamic parameters Suppose we need routes: const routes = [ // Dynamic segments start with a colon { path: '/users/:id', component: User }, // Use regular expression `()` The contents will be passed to the previous pathMatch // Value under route.params.pathMatch { path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound }, ] When matching, the parameters are mapped to
Match List
When using routes with parameters, be aware that: Since the same component instance will be reused, the component lifecycle hooks will not be called. But we can monitor the route Use watch to monitor dynamic parameters Modify <template> <div>User component</div> <p>Current user: {{ uid }}</p> <router-link to="/user/lczmx">lczmx</router-link> <router-link to="/user/jack">jack</router-link> </template> <script lang="ts"> import { defineComponent, watch, ref } from "vue"; import { useRouter } from "vue-router"; export default defineComponent({ name: "User", setup() { const router = useRouter(); const uid = ref(router.currentRoute.value.params.uid); watch( // Listen for non-responsive data() => router.currentRoute.value, (val) => { // Modify uid uid.value = val.params.uid; } ); return { // Returned data uid, }; }, }); </script> Using the Combination API to monitor dynamic parametershttps://next.router.vuejs.org/en/guide/advanced/composition-api.html Redirect The following uses all the parameters of const routes = [ { path: "/", // Method 1: hard-code the URL // redirect: "/home", // redirect to "/home" when accessing "/" // Method 2: Jump to the corresponding named route redirect: { name: "home" }, //Writing method 3 defines a method //This method can also return a relative path/* redirect: to => { // The method receives the target route as parameter "to" // return redirected string path/path object // query specifies parameters return { path: '/home', query: { q: to.params.searchText } } }, */ }, { path: "/home", name: "home", component: Home } ]
Naming and AliasesNamed Routes
const routes = [ { path: '/user/:username', name: 'user', component: User } ] The use of <template> <div>User component</div> <p>Current user: {{ uid }}</p> <router-link :to="{ name: 'user', params: { uid: 'lczmx' } }" >lczmx</router-link > <router-link :to="{ name: 'user', params: { uid: 'jack' } }" >jack</router-link > </template> Use in router.push({ name: 'user', params: { uid: 'lczmx' } }) Named Views
For example Define the routes: import { createRouter, createWebHashHistory } from "vue-router" import Home from '../components/Home.vue' import About from '../components/About.vue' import User from '../components/User.vue' const routes = [ { path: "/", components: default: Home, // default uses the Home component a: About, // a uses the About component b: User, // b uses the User component }, }, { path: "/home", components: default: About, // Use the About component by default a: Home, // a uses the Home component b: User, // b uses the User component }, }, ] export const router = createRouter({ history: createWebHashHistory(), routes: routes }) Modify <template> <div>{{ appMessage }}</div> <!-- router-link will be rendered as a tag--> <router-link to="/">/</router-link> <router-link to="/home">/home</router-link> <!-- Routing exit --> <!-- Components matched by the route will be rendered here--> <!-- default --> <router-view></router-view> <router-view name="about"></router-view> <router-view name="user"></router-view> </template> <script lang="ts"> import { defineComponent } from "vue"; export default defineComponent({ name: "App", setup() { const appMessage = "App component"; return { //Returned data appMessage, }; }, }); </script> <style> /* Add styles */ #app { text-align: center; margin-top: 50px; } a { margin: 30px; display: inline-block; } </style> Other Components <template> <div>about component</div> </template> <template> <div>home component</div> </template> <template> <div>user component</div> </template> Start the service and access vue As shown:
Aliases
const routes = [ // You can access "/home" or "/" // and the access path will not change{ path: "/home", name: "home", component: Home, alias: "/" } Nested Routes Previously, we defined But if we need to render in other components, we need nested routing
example: import { createRouter, createWebHashHistory } from "vue-router" import Home from '../components/Home.vue' import About from '../components/About.vue' import User from '../components/User.vue' import UserHome from '../components/UserHome.vue' import UserSettings from '../components/UserSettings.vue' import UserProfile from '../components/UserProfile.vue' const routes = [ // You can access "/home" or "/" // and the access path will not change { path: "/home", name: "home", component: Home, alias: "/" }, { path: "/about", name: "about", component: About }, { path: "/user/:uid", // dynamic parameter name: "user", component: User, // Routers that are nested in router-view rendering children: [ // Match URLs like /user/lczmx { path: "", component: UserHome }, // Match URLs like /user/lczmx/settings { path: "settings", component: UserSettings, name: "user-settings" }, // Match URLs like /user/lczmx/profile { path: "profile", component: UserProfile, name: "user-profile" } ] } ] export const router = createRouter({ history: createWebHashHistory(), routes: routes })
<template> <div> <router-link :to="{ name: 'user-settings' }">settings</router-link> <router-link :to="{ name: 'user-profile' }">profile</router-link> </div> <router-view></router-view> </template> <template> <div>User homepage</div> </template> <template> <div>User details page</div> </template> <template> <div>User settings page</div> </template> Start and access Test in browser: Programmatic Routing That is, instead of using the a tag, the route is changed through <template> <div>about component</div> <button @click="changeRouter">Change route</button> </template> <script lang="ts"> import { defineComponent } from "vue"; import { useRouter } from "vue-router"; export default defineComponent({ name: "About", setup() { // Get the router object const router = useRouter(); const changeRouter = () => { /* Example of modifying routes */ // 1 string path router.push("/users/lczmx"); // 2 Object with path router.push({ path: "/users/lczmx" }); // 3 named routes, and added parameters to let the routes build the url router.push({ name: "user", params: { username: "lczmx" } }); // 4 with query parameters, the result is /register?plan=private router.push({ path: "/register", query: { plan: "private" } }); // 5 with hash, the result is /about#team router.push({ path: "/about", hash: "#team" }); // 6 We can build the url manually, but we have to handle the encoding ourselves const username = "lczmx"; router.push(`/user/${username}`); // -> /user/lczmx // Similarly router.push({ path: `/user/${username}` }); // -> /user/lczmx // If possible, use `name` and `params` to benefit from automatic URL encoding router.push({ name: "user", params: { username } }); // -> /user/lczmx // 7 `params` cannot be used with `path`, otherwise `params` will be ignored router.push({ path: "/user", params: { username } }); // -> /user // 8 replace is true and does not add to history router.push({ path: "/home", replace: true }); // Equivalent to router.replace({ path: "/home" }); // 9 Across history // Move forward one record, same as router.forward() router.go(1); // Return a record, same as router.back() router.go(-1); // Go forward 3 records router.go(3); // If there are not so many records, fail silently router.go(-100); router.go(100); }; return { //Returned data changeRouter, }; }, }); </script> <style> button { margin: 30px; } </style>
The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM. You may also be interested in:
|
>>: Map the mouse position in CSS and control the page elements by moving the mouse (example code)
1: Install SVN yum install -y subversion 2. Creat...
Situation description: The database was started a...
Table of contents MySQL crash recovery process 1....
Table of contents 1. Database design 2. Front-end...
Download MySQL https://dev.mysql.com/downloads/my...
Every website usually encounters many non-search ...
1. Command Introduction time is used to count the...
This article example shares the specific code of ...
If your DOCTYPE is as follows: Copy code The code ...
<br />Question: How to write in HTML to jump...
1. Background Sysbench is a stress testing tool t...
In MySQL operation and maintenance, a R&D col...
Table of contents 1. Timer monitoring 2. Event mo...
Problem: vue-cil3 runs with warnings potentially ...
background: Sometimes we need to display json dat...