search
HomeWeb Front-endJS TutorialHow to use vue scaffolding and vue-router

This time I will show you how to use vue scaffolding and vue-router, and what are the precautions for using vue scaffolding and vue-router. The following is a practical case. Let’s take a look. .

First of all, under the premise that vue-cli has been installed, and after

cnpm install (the official website uses npm, but it is recommended to use cnpm here, which is faster than npm and npm sometimes There is a phenomenon of getting stuck). Here is a small reminder about whether to turn on eslint. This is a tool to standardize the code you write. For newbies, it is recommended to turn it off, otherwise the code written will not comply with its specifications. Your compiler will keep reporting errors, as shown below

After installing the scaffolding, it will look like this

Terminal input

npm run dev, then open localhost:8080 and you can see the project running

Let’s roughly analyze some of the more commonly used files, as shown below

1.build: Mainly used to configure the build project and webpack

2.config: Project development configuration

3.npm or cnpm Downloaded dependency package

4. Your source code

5. Static folder, webpack will not package this file when packaging

6. Outermost page Generally, the title and so on are set here

7. Store the json data of the npm dependency package you want

After roughly introducing the project structure, let’s take a look at the source code of its page!

Start with this App.vue. This file is only for the external index, which means that the index contains all pages, and App.vue contains pages except index, that is Route nesting, as will be mentioned later, the files created here are all file names.vue. The HTML format of the page is a template tag containing a p, which is equivalent to a componentized form, and the content of the component is written in this p (A page must have only one template containing one p, and the content is written in this p, otherwise an error will be reported), and this router-view tag is a sub-page under the current page. It can be understood that this router-view is another page. Contained by the current page, somewhat similar to the function of the ifame tag.

css, js format

Now let’s take a look at the HelloWorld.vue page, where the js and css code placement format has been written for you. Yes, just write it in this format. What needs to be reminded is the scoped attribute in the style tag. If this is not written, the style of this style will affect all sub-routes of this page. If it is added, this style will only apply to the current The page works

After reading the page, let’s take a look at the routing configuration as shown below

The routing path is under the router. When you first open it, you will see an error. , it’s actually not a

grammar error, it’s because the compiler compiles the es5 syntax by default, and the vue scaffolding uses the es6 syntax. The compiler I use is webStorm, and it just needs to be set up.

Кратко представим структуру маршрутизаторов. В основном она используется для настройки маршрутов. Как упоминалось выше, все подмаршруты находятся в App.vue. Все App.vue – это самый внешний родительский маршрут. Они хранятся здесь в маршрутах. Он — это массив маршрутов, а путь — это путь, по которому вы хотите получить доступ к созданной вами странице.Здесь написана последовательность корневых путей, поэтому, если вы напрямую обращаетесь к localhost:8080, страница с файлом HelloWorld.vue, вставленным в App. vue (это эквивалентно вложению маршрутизации), имя не имеет значения по сравнению с его присвоением имени. Компонент эквивалентен странице, на которую вы хотите сослаться. Здесь упоминается страница HelloWorld.vue, в основном импорт выше. HelloWorld здесь — это переменная, соответствующая указанному выше файлу Path

Сейчас я научу вас, как создавать файл и настраивать маршрутизацию

Сначала создайте файл с суффиксом vue и напишите самый простой HTML структура

Затем настройте его маршрутизацию.Сначала введите этот файл с помощью импорта, а затем заполните путь для доступа к этому файлу.Я использую /test.Чтобы открыть этот маршрут, введите localhost:8080/#/test.В этом Импортированный файл переносится в компонент

и вводится URL-адрес.Страница с test.vue, вложенная в APP.vue появится

Вложенность маршрутов vue по умолчанию заключается в том, что все страницы вложены в страницу App.vue. Теперь я научу вас, как свободно вкладывать свои собственные страницы. Теперь я вложу тестовую страницу в страницу HelloWorld.vue

Сначала добавлю метку представления маршрутизатора под интерфейсом HelloWorld.vue

Затем настрою подмаршрут HelloWorld.vue

Таким образом, localhost:8080/#/test — это страница, на которой APP.vue вкладывает HelloWorld.vue и test.vue, как показано ниже

#Это так просто Вложение маршрутов завершено. Давайте поговорим о переходе маршрутизации. Например, если вы привязываете функцию к кнопке и нажимаете кнопку, чтобы перейти к тестовую страницу, вы можете использовать

this.$router.push({path:'/test'})

в функции, если хотите вернуться на предыдущую страницу. Общее содержание страницы —

this.$router.go(-1)

. Если есть какие-либо ошибки или сожаления, пожалуйста, простите меня или свяжитесь со мной, чтобы мы могли больше общаться!

Я считаю, что вы освоили этот метод после прочтения примера, описанного в этой статье. Для получения более интересной информации обратите внимание на другие статьи по теме на китайском веб-сайте php! Рекомендуется к прочтению

#Как справиться с конфликтом между событиями двойного щелчка и щелчка в JS

###Элегантное использование CSS-модули в методе Vue#########

The above is the detailed content of How to use vue scaffolding and vue-router. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Vue应用中遇到vue-router的错误“NavigationDuplicated: Avoided redundant navigation to current location” – 怎么解决?Vue应用中遇到vue-router的错误“NavigationDuplicated: Avoided redundant navigation to current location” – 怎么解决?Jun 24, 2023 pm 02:20 PM

Vue应用中遇到vue-router的错误“NavigationDuplicated:Avoidedredundantnavigationtocurrentlocation”–怎么解决?Vue.js作为快速而灵活的JavaScript框架在前端应用开发中越来越受欢迎。VueRouter是Vue.js的一个代码库,用于进行路由管理。然而,有时

一文深入详解Vue路由:vue-router一文深入详解Vue路由:vue-routerSep 01, 2022 pm 07:43 PM

本篇文章带大家详解Vue全家桶中的Vue-Router,了解一下路由的相关知识,希望对大家有所帮助!

在Vue应用中使用vue-router时出现“Error: Failed to resolve async component: xxx”怎么解决?在Vue应用中使用vue-router时出现“Error: Failed to resolve async component: xxx”怎么解决?Jun 24, 2023 pm 06:28 PM

在Vue应用中使用vue-router是一种常见的方式来实现路由控制。然而,在使用vue-router的时候,有时候会出现“Error:Failedtoresolveasynccomponent:xxx”的错误,这是由于异步组件加载错误导致的。在本文中,我们将探讨这个问题,并提供解决方案。理解异步组件加载原理在Vue中,组件可以被同步或异步地创建

Vue-Router: 如何使用路由元信息来管理路由?Vue-Router: 如何使用路由元信息来管理路由?Dec 18, 2023 pm 01:21 PM

Vue-Router:如何使用路由元信息来管理路由?简介:Vue-Router是Vue.js官方的路由管理器,它可以帮助我们快速构建单页应用程序(SPA)。除了常见的路由功能外,Vue-Router还支持使用路由元信息来管理和控制路由。路由元信息是可以附加到路由上的自定义属性,它可以帮助我们实现一些特殊的逻辑或者权限控制。一、什么是路由元信息?路由元信息是

在Vue应用中使用vue-router时出现“Error: Avoided redundant navigation to current location”怎么解决?在Vue应用中使用vue-router时出现“Error: Avoided redundant navigation to current location”怎么解决?Jun 24, 2023 pm 05:39 PM

在Vue应用中使用vue-router时,有时候会出现“Error:Avoidedredundantnavigationtocurrentlocation”的错误信息。这个错误信息的意思是“避免了到当前位置的冗余导航”,通常是因为重复点击了同一个链接或者使用了相同的路由路径导致的。那么,怎么解决这个问题呢?使用exact修饰符在定义router

如何在 Windows 11 中按需使用 OneDrive 的文件如何在 Windows 11 中按需使用 OneDrive 的文件Apr 14, 2023 pm 12:34 PM

<p>Windows 系统上的 OneDrive 应用程序允许您将文件存储在高达 5 GB 的云上。OneDrive 应用程序中还有另一个功能,它允许用户选择一个选项,是将文件保留在系统空间上还是在线提供,而不占用您的系统存储空间。此功能称为按需文件。在这篇文章中,我们进一步探索了此功能,并解释了有关如何在 Windows 11 电脑上的 OneDrive 中按需使用文件的各种选项。</p><h2>如何使用 On

在Vue应用中使用vue-router时出现“Error: Invalid route component: xxx”怎么解决?在Vue应用中使用vue-router时出现“Error: Invalid route component: xxx”怎么解决?Jun 25, 2023 am 11:52 AM

Vue是一个流行的前端框架,它允许开发者快速构建高效、可重用的web应用程序。Vue-router是Vue框架中的一个插件,可以帮助开发者轻松管理应用的路由和导航。但是,在使用Vue-router的过程中,有时候会遇到一个常见的错误:“Error:Invalidroutecomponent:xxx”。这篇文章将介绍这个错误的原因和解决方法。原因在Vu

在Vue应用中使用vue-router时出现“Uncaught TypeError: Cannot read property 'push' of undefined”怎么解决?在Vue应用中使用vue-router时出现“Uncaught TypeError: Cannot read property 'push' of undefined”怎么解决?Aug 18, 2023 pm 09:24 PM

最近我尝试在Vue应用中使用vue-router,但遇到了一个问题:“UncaughtTypeError:Cannotreadproperty'push'ofundefined”。这个问题的原因是什么,以及如何解决呢?首先,让我们了解一下vue-router。vue-router是Vue.js官方的路由管理插件,可以帮助我们构建单页应用(SPA

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)