博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Vue Router入门
阅读量:2514 次
发布时间:2019-05-11

本文共 13631 字,大约阅读时间需要 45 分钟。

Vue is already a great Javascript library that allows you to create some really cool, dynamic, front-end applications. Vue is also great for single page applications (SPA). SPAs work a little differently that your standard backend web application built in something like PHP. Instead of making requests to different routes on the backend and getting a fully rendered page as a response, a SPA does all the page rendering on the front-end and only sends requests to the server when new data is needed or needs to be refreshed or saved.

Vue已经是一个很棒的Javascript库,它使您可以创建一些非常酷的,动态的前端应用程序。 Vue对于单页应用程序(SPA)也非常有用。 SPA与使用PHP之类的标准后端Web应用程序的工作方式略有不同。 SPA不会在后端向不同的路由发出请求并获得完整呈现的页面作为响应,而是在前端执行所有页面的呈现,并且仅在需要新数据或需要刷新数据时才将请求发送到服务器,或者保存。

This can improve the responsiveness of your web application because you can render the pages once and display them dynamically based on the current context of the application. In order to make this work, you need a way to distinguish the different views or pages from eachother. In SPAs this is done with a router. Luckily Vue has a fully supported first-party router library called vue-router.

这可以提高Web应用程序的响应能力,因为您可以一次渲染页面并根据应用程序的当前上下文动态显示它们。 为了使这项工作有效,您需要一种将彼此不同的视图或页面区分开的方法。 在SPA中,这是通过路由器完成的。 幸运的是,Vue有一个完全支持的第一方路由器库,称为vue-router。

In this tutorial we'll setup a simple SPA that will show some information about popular cryptocurrencies. We'll call it "Crypto Info". It will have a few pages and link those pages using vue-router. You should already be familiar with Vue as well as creating and using Vue components. Having experience with .vue files is helpful but not required.

在本教程中,我们将设置一个简单的SPA,其中将显示有关流行的加密货币的一些信息。 我们将其称为“加密信息”。 它将有几个页面,并使用vue-router链接这些页面。 您应该已经熟悉Vue以及创建和使用Vue组件。 拥有.vue文件的经验会有所帮助,但不是必需的。

( )

To get started, let's use the handy Vue command line installer. Open a terminal and run the following.

首先,让我们使用方便的Vue命令行安装程序。 打开一个终端并运行以下命令。

# install vue-cli$ npm install --global vue-cli# create a new project using the "webpack" template$ vue init webpack router-app

When prompted, answer the questions displayed on the screen like so. Make sure to answer "yes" for installing vue-router.

出现提示时,请像这样回答屏幕上显示的问题。 确保回答“是”以安装vue-router。

This willinstall Vue 2.x version of the template. For Vue 1.x use: vue init webpack#1.0 router-app? Project name router-app 
? Project description A Vue.js project
? Author
? Vue build standalone
? Install vue-router? Yes? Use ESLint to lint your code? No? Setup unit tests with Karma + Mocha? No? Setup e2e tests with Nightwatch? No

Once the app is setup, install all the dependencies and start up a dev server.

设置好应用程序后,安装所有依赖项并启动开发服务器。

# install dependencies and go!$ cd router-app$ npm install$ npm run dev

You should now be able to point a browser at and see something like this.

现在,您应该可以将浏览器指向并看到类似的内容。

( )

The great thing about the Vue command line tool is that it will wire up vue-router for us. To get a better understanding of how it works, we can take a look the boilerplate that was created. Open /src/router/index.js

Vue命令行工具的伟大之处在于它将为我们连接vue-router。 为了更好地了解其工作原理,我们可以看一下创建的样板。 打开/src/router/index.js

import Vue from 'vue'import Router from 'vue-router'import Hello from '@/components/Hello'Vue.use(Router)export default new Router({
routes: [ {
path: '/', name: 'Hello', component: Hello } ]})

The first two lines are importing vue and vue-router. The third line is importing a component called Hello. We will discuss why in a bit. The @ is just a nice alias for the /src directory that was setup in webpack by the Vue command line tool.

前两行是导入vue和vue-router。 第三行是导入一个名为Hello的组件。 我们稍后将讨论原因。 @只是Vue命令行工具在webpack中设置的/src目录的好别名。

Next we tell Vue to use the vue-router plugin. Finally the router is configured with a single route. The router uses Vue components as pages. In the above example we want to render the Hello component whenever a user navigates to the / route.

接下来,我们告诉Vue使用vue-router插件。 最终,路由器配置了一条路由。 路由器将Vue组件用作页面。 在上面的示例中,我们希望在用户导航到/路线时呈现Hello组件。

Next open /src/main.js

接下来打开/src/main.js

// The Vue build version to load with the `import` command// (runtime-only or standalone) has been set in webpack.base.conf with an alias.import Vue from 'vue'import App from './App'import router from './router'Vue.config.productionTip = false/* eslint-disable no-new */new Vue({
el: '#app', router, template: '
', components: {
App }})

The first line is importing Vue again. The second line is bringing in a component called App. This will serve as the root component for the application. The third line is importing the router setup we looked at earlier. The next line tells Vue whether or not to show tips and warnings in the developer console of your browser. In this case it is set to false.

第一行是再次导入Vue。 第二行引入了一个名为App的组件。 这将用作应用程序的根组件。 第三行是导入我们之前看过的路由器设置。 下一行告诉Vue是否在浏览器的开发人员控制台中显示提示和警告。 在这种情况下,它设置为false。

Finally a new Vue instance is created and mounted to the #app div in our html and then it instantiated the App component. We also inject the router configuration from earlier.

最后,在我们的html中创建一个新的Vue实例并将其安装到#app div中,然后实例化App组件。 我们还从早期注入了路由器配置。

Now open /src/App.vue

现在打开/src/App.vue

This, like I mentioned before, is the root component. It will serve as the point from which our page components will be rendered. Note that all the components we will use are in .vue files which allows us to save the template, javascript and styling into a single file.

正如我之前提到的,这是根组件。 它将作为渲染页面组件的起点。 请注意,我们将使用的所有组件都位于.vue文件中,这使我们可以将模板,javascript和样式保存到单个文件中。

Within the <template> tag we just have some simple markup. The important piece though is the <router-view> tag. The router uses this tag as a container for rendering the different components tied to the different routes. Just think of it as a placeholder.

<template>标记内,我们只有一些简单的标记。 不过,重要的部分是<router-view>标记。 路由器将此标签用作容器,以呈现绑定到不同路由的不同组件。 只需将其视为占位符即可。

The <script> tag just contains a simple Vue component object that does nothing. The <style> tag just contains some nice styling boilerplate provided by the Vue command line tool.

<script>标记仅包含一个不执行任何操作的简单Vue组件对象。 <style>标签仅包含Vue命令行工具提供的一些漂亮的样式样板。

Now open /src/components/Hello.vue

现在打开/src/components/Hello.vue

This is very similar to the App component. Again, within the <template> tag there is the HTML markup for the component. In this case it's all the links and text shown when we pointed our browser to . This is because in our router config, we specified that / or the root path of our application should point to Hello.vue.

这与App组件非常相似。 同样,在<template>标记内,有该组件HTML标记。 在这种情况下,当我们将浏览器指向时,将显示所有链接和文本。 这是因为在我们的路由器配置中,我们指定/或应用程序的根路径应指向Hello.vue

Now let's get rid of the default content and create a simpler home page. Edit Hello.vue to look like the following:

现在,让我们摆脱默认内容,创建一个更简单的主页。 编辑Hello.vue如下所示:

If you reload, you should now see a page like this.

如果重新加载,现在应该会看到类似的页面。

( )

Now let's create a new page and add some links for navigating between the two. Open /src/router/index.js and edit it to look like the following.

现在让我们创建一个新页面,并添加一些链接以在两者之间进行导航。 打开/src/router/index.js并对其进行编辑,如下所示。

import Vue from 'vue'import Router from 'vue-router'import Hello from '@/components/Hello'import About from '@/components/About'Vue.use(Router)export default new Router({
routes: [ {
path: '/', name: 'Hello', component: Hello }, {
path: '/about', name: 'About', component: About } ]})

We've added a new route /about that points to a new component called About. We've also imported the new component at the top. We will create this shortly.

我们添加了一条新路线/about ,该路线指向名为About的新组件。 我们还在顶部导入了新组件。 我们将很快创建它。

Now open /src/App.vue and edit the <template> section to look like this.

现在打开/src/App.vue并编辑<template>部分,如下所示。

As you can see, we added two <router-link> tags using two different methods. The router uses <router-link> to create html links to routes you created. The first method uses a named route. If you recall, in /src/router/index.js we added the name parameter to our routes. In this case the name of the route is Hello just like the component it points to. The second method is the standard method and just specifies the path we want to link to.

如您所见,我们使用两种不同的方法添加了两个<router-link>标记。 路由器使用<router-link>创建指向您创建的路由的html链接。 第一种方法使用命名路由。 您还记得吗,在/src/router/index.js我们在/src/router/index.js添加了name参数。 在这种情况下,路由的名称就像它指向的组件一样是Hello 。 第二种方法是标准方法,仅指定我们要链接的路径。

If you refresh the browser, you should see the original welcome page but with two links added.

如果刷新浏览器,应该会看到原始的欢迎页面,但添加了两个链接。

If you click the About link, you will get a blank page. This is because we haven't created the component yet. Let's fix this be creating /src/components/About.vue.

如果单击About链接,则将显示空白页。 这是因为我们尚未创建组件。 让我们通过创建/src/components/About.vue来解决此/src/components/About.vue

Now if you refresh the browser and click About you should see the new page.

现在,如果刷新浏览器并单击“ About ,则应该会看到新页面。

( )

So we can create a new page and a route to point to it but what about passing parameters? We'll need a page that displays some useful info about various crypto currencies based on a string id passed in the URL. Let's make that happen. Open /src/router/index.js again and add a third route.

因此,我们可以创建一个新页面和指向该页面的路线,但是传递参数呢? 我们需要一个页面,该页面根据URL中传递的字符串ID显示一些有关各种加密货币的有用信息。 让我们做到这一点。 再次打开/src/router/index.js并添加第三条路由。

...import Coins from '@/components/Coins'...export default new Router({
routes: [ ... {
path: '/coins/:id', name: 'Coins', component: Coins } ]})

In order to display up-to-date information on the various currencies, we'll use the popular http client to fetch data from the free API. We'll accept a string parameter in the URL called :id. This will be passed to the API to retrieve the relevant data.

为了显示有关各种货币的最新信息,我们将使用流行的 http客户端从免费的 API获取数据。 我们将在URL中接受一个名为:id的字符串参数。 这将传递给API以检索相关数据。

First we need to install axios.

首先,我们需要安装axios。

npm install --save axios

Next create a file called /src/components/Coins.vue

接下来创建一个名为/src/components/Coins.vue的文件

You'll notice that in the data object of our component, we declare an empty object called coin. This will store our coin information after it is fetched. In the <template> section we have some markup to display the name, symbol and US dollar price of the coin. The created method is a special hook used by Vue that is called before the component is rendered. In this case we are calling the fetchData method which is making a GET request with axios to the Coin Market Capitalization API and passing the :id parameter at the end.

您会注意到,在组件的数据对象中,我们声明了一个名为coin的空对象。 取回后,这将存储我们的硬币信息。 在<template>部分,我们有一些标记来显示代币的名称,符号和美元价格。 created方法是Vue使用的特殊钩子,在呈现组件之前会被调用。 在这种情况下,我们调用fetchData方法,该方法使用axios向Coin Market Capitalization API发出GET请求,并在末尾传递:id参数。

We get the parameter from the $route object params property. This object is auto injected by VueRouter. The paramater we want is the :id parameter which we defined in our router file. On success, as defined in the the then promise method, we save the data returned into our coin object. This is then rendered on in the template.

我们从$route对象params属性获取参数。 该对象由VueRouter自动注入。 我们想要的参数是我们在路由器文件中定义的:id参数。 成功后,如then promise方法中所定义,我们将返回的数据保存到我们的coin对象中。 然后将其呈现在模板中。

One other thing we need is to add a watch hook for the $route object. VueRouter components are only rendered once for speed. If you need to rerender, you need to do that manually so in this case we want to rerender when the :id parameter in $route changes and then fetch new data.

我们需要做的另一件事是为$route对象添加一个watch钩。 VueRouter组件仅渲染一次以提高速度。 如果需要重新渲染,则需要手动进行,因此在这种情况下,我们要在$route:id参数更改后重新渲染,然后获取新数据。

Now lets create a few more links in /src/App.vue to see how this new page might be used.

现在,让我们在/src/App.vue创建更多链接,以了解如何使用此新页面。

If you refresh the browser and click on Ethereum you should see something like this.

如果刷新浏览器并单击Ethereum您应该会看到类似这样的信息。

Now click on Bitcoin and you should see relevant information for that coin as well. If you want to try out other coins, have a look at and paste a few ids from the list into the URL of our app.

现在单击Bitcoin ,您Bitcoin看到该代币的相关信息。 如果您想尝试其他硬币,请查看并将列表中的一些ID粘贴到我们应用的URL中。

( )

That's how easy it is to get started with Vue Router. There are a bunch of other great features as well and you can read about them in the official documentation. I hope this tutorial is enough to get you started making some cool SPAs in Vue!

这就是开始使用Vue Router的容易程度。 另外还有许多其他很棒的功能,您可以在官方文档中阅读它们。 我希望本教程足以使您开始在Vue中制作一些很酷的SPA!

翻译自:

转载地址:http://mguwd.baihongyu.com/

你可能感兴趣的文章
【MM系列】在SAP里查看数据的方法
查看>>
C#——winform
查看>>
CSS3 transform制作的漂亮的滚动式导航
查看>>
《小强升职记——时间管理故事书》读书笔记
查看>>
Alpha 冲刺(3/10)
查看>>
Kaldi中的Chain模型
查看>>
spring中的ResourceBundleMessageSource使用和测试示例
查看>>
css规范 - bem
查看>>
SQL 通用数据类型
查看>>
UVALive 6145 Version Controlled IDE(可持久化treap、rope)
查看>>
mysql 将两个有主键的表合并到一起
查看>>
底部导航栏-----FragmentTabHost
查看>>
在linux中安装jdk以及tomcat并shell脚本关闭启动的进程
查看>>
apk,task,android:process与android:sharedUserId的区别
查看>>
MySQL 同主机不同数据库之间的复制
查看>>
matplotlib函数理解
查看>>
前端实现文件的断点续传
查看>>
转:spring4.0之二:@Configuration的使用
查看>>
【Android开发】交互界面布局详解
查看>>
状态机编程思想(1):括号内外字符串统计
查看>>