vue.js中的路由_如何在Vue.js中使用路由来创建更好的用户体验

vue.js中的路由

Vue.js is a great JavaScript Framework created by Evan You. It’s used to build single web page apps and flexible components, and it’s one of the most required skills in Front End Web development. You can learn more about Vue.js here.

Vue.js是Evan You创建的一个很棒JavaScript框架。 它用于构建单个网页应用程序和灵活的组件,并且是前端Web开发中最需要的技能之一。 您可以在此处了解有关Vue.js的更多信息。

Vue.js provides a bunch of features that allow you to build reusable web components. Routing is one of those methods. It allows the user to switch between pages without refreshing the page. This is what makes navigation easy and really nice in your web applications.

Vue.js提供了许多功能,可让您构建可重复使用的Web组件。 路由是这些方法之一。 它允许用户在页面之间切换而无需刷新页面。 这就是使导航轻松并且在您的Web应用程序中非常好的原因。

So in this article, I’ll explain how Vue.js routers work by building a Vue template as an example.

因此,在本文中,我将以构建Vue模板为例来说明Vue.js路由器如何工作。

入门 (Getting started)

So, let’s get started with our Vue.js Router project by installing and creating a new Vue.js project. We need to have Node.js installed. We will be using vue-cli to generate a new Vue.js project. Follow the steps given below:

因此,让我们通过安装并创建一个新的Vue.js项目开始我们的Vue.js Route r项目。 我们需要安装Node.js。 我们将使用vue-cli生成一个新的Vue.js项目。 请按照以下步骤操作:

Type the following code in your terminal and run:

在终端中输入以下代码并运行:

vue init webpack vue-router
//cd vue-router//npm run dev

Browse to http://localhost:8080

浏览到http:// localhost:8080

Open the app in your text editor. Inside the components folder, open the HellowWorld.vue file and follow these steps:

在文本编辑器中打开该应用。 在components文件夹中,打开HellowWorld.vue文件,然后执行以下步骤:

  • Rename HellowWorld.vue to home.vue. Remove all the code and replace it with this:

    HellowWorld.vue重命名为home.vue 。 删除所有代码并将其替换为:

<template>  <div class="home">    <h1>Home</h1>  </div></template>
<script>export default {  name: 'home',  data () {    return {      msg: 'Welcome to Your Vue.js App'    }  }}</script>
<!-- Add "scoped" attribute to limit CSS to this component only --><style scoped>
</style>
  • Go to index.js inside the router folder and replace HelloWorld with home:

    转到router文件夹内的index.js并将HelloWorld替换为home

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

The App.vue file should look like this:

App.vue文件应如下所示:

<template>  <div id="app">        <router-view/>  </div></template>
<script>export default {  name: 'App'}</script>
<style>#app {  }</style>

And now let’s write our code!

现在,让我们编写代码!

We are now going to add a Bootswatch template. You can choose any template you like. I’ll choose Cosmo. Click Ctrl + U to view the code source and just copy the Navbar (we just need the navbar). Paste this code into App.vue component.

现在,我们将添加一个Bootswatch模板。 您可以选择任何喜欢的模板。 我选择Cosmo 。 按Ctrl + U查看源代码和刚才复制的Navbar (我们只需要导航栏)。 将此代码粘贴到App.vue中 零件。

Here we are ?

我们来了 ?

Next, we’re gonna create three other components: Blog,Services and Contact.

接下来,我们将创建其他三个组件: BlogServicesContact

Inside the components folder, create new file, name it blog.vue, and push this code into it:

在components文件夹中,创建一个新文件,将其命名为blog.vue ,并将以下代码推送到其中:

<template> <div class="blog">  <h1>{{blog}}</h1> </div></template><script> export default{  name:'blog',  data (){   return{    title:'Blog'   }  } }</script>
<style scoped> </style>

If you want to do the same thing for the service and contact component, you must have these files in your component folder:

如果要对服务和联系组件执行相同的操作,则必须在组件文件夹中具有以下文件:

  • home.vue

  • blog.vue

    blog.vue
  • services.vue

    services.vue
  • contact.vue

    contact.vue

路由器配置 (Routers config)

Now after creating these four components, we need to configure the routers so that we can navigate between the components.

现在,在创建了这四个组件之后,我们需要配置路由器,以便我们可以在这些组件之间导航。

So how we can navigate to each components using the routers?

那么我们如何使用路由器导航到每个组件?

We need to learn the rules of routing. Now, we have to do some modifications inside the router folder, so open index.js

我们需要学习路由规则。 现在,我们必须在router文件夹中进行一些修改,因此打开index.js

Follow these steps:

跟着这些步骤:

  • First import your components into index.js. Import all the components using the import method.

    首先将您的组件导入index.js。 使用import方法导入所有组件。

import home from '@/components/home'import blog from '@/components/blog'import services from '@/components/services'import contact from '@/components/contact'
import Vue from 'vue'import Router from 'vue-router'
// use routerVue.use(Router)

If you have installed Vue with vue-cli, you will have the vue-router module imported by default.

如果已将vue与vue-cli一起安装,则默认情况下将导入vue-router模块。

  • Finally, inside the router folder, we have to configure the routers to make them work. The router method takes an Array of objects which in turn takes each component’s properties:

    最后,在路由器文件夹中,我们必须配置路由器以使其正常工作。 router方法采用对象数组,而对象数组又采用每个组件的属性:
export default new Router({  routes: [    {      path: '/',      name: 'home',      component: home    },    {      path: '/blog',      name: 'blog',      component: blog    },    {      path: '/services',      name: 'services',      component: services    },    {      path: '/contact',      name: 'contact',      component: contact    }  ]})
  • path : the path of the component

    path :组件的路径

  • name: the name of the component

    name :组件的名称

  • component : the view of the component

    componentcomponent的视图

To make any component the default component, set slash(‘/’) to the path property:

要将任何组件设置为默认组件,请​​将slash('/')设置为path属性:

path:'/'

In our example, we set the home page as the default page. Now, when you open the the project in the browser, the first page that will appear is the home page.

在我们的示例中,我们将主页设置为默认页面。 现在,当您在浏览器中打开项目时,将显示的第一页是主页。

{path:'/',name:'home',component:home}

The vue-router has more advanced parameters and methods, but we are not jumping into this section at this point.

vue-router具有更高级的参数和方法,但目前我们不会跳到本节。

This is the list of properties and methods that you can use with vue-router:

这是可以与vue-router一起使用的属性和方法的列表:

Now you can browse to any components by typing the name of the component!

现在,您可以通过键入组件名称浏览到任何组件!

Now we are going to set up the navigation through the Navbar that we created using the router-link element.

现在,我们将通过使用创建的导航栏来设置导航 路由器链接元素。

To do that, we should replace the </a> element by <router-link>&lt;/router/link> like this:

为此,我们应将< / a>元素替换为< nt by <router-link>&l t; / router / link>,如下所示:

<li class="nav-item">  <router-link class="nav-link" to="/blog">Blog</router-link></li><li class="nav-item">  <router-link class="nav-link" to="/services">Services</router-link> </li><li class="nav-item">   <router-link class="nav-link" to="/contact">contact</router-link> </li>

The router-link takes the to='path' attribute that takes the path of the component as a value.

路由器链接采用to='path'属性,该属性将组件的路径作为值。

路由器视图 (Router-view)

You will find the <router-view> tag in the App.vue file. It’s basically the view where the components are rendered. It’s like the main div that contains all the components, and it returns the component that match the current route. We will discuss route-view in the next part when we use the animation transition .

您将n the A pp.vue文件中找到<router-vi ew>标签。 基本上是渲染组件的视图。 就像包含所有组件的主div一样,它返回与当前路线匹配的组件。 在下一部分中,当我们使用动画过渡时,我们将scuss rout电子视图。

使用路由器内部的参数 (Using the parameters inside the routers)

At this point, we will use parameters to navigate to specific components. The parameters make the routing dynamic.

在这一点上,我们将使用参数导航到特定组件。 这些参数使路由动态化。

To work with parameters, we are gonna create a list of products and an array of data. When you click on the link of any product, it will take us to the page details through a parameter.

为了使用参数,我们将创建产品列表和数据数组。 当您单击任何产品的链接时,它将通过参数将我们带到页面详细信息。

In this situation, we are not going to use a database or API to retrieve the products’ data. So what we have to do is create an Array of products that will act as a database.

在这种情况下,我们将不会使用数据库或API来检索产品的数据。 因此,我们要做的是创建一个将用作数据库的产品数组。

Inside the home.vue component, put the Array within the data() method just like this:

home.vue组件内部,将Array放在data()方法中,如下所示:

export default {  name: 'home',  data () {    return {      title: 'Home',      products:[      {        productTitle:"ABCN",        image       : require('../assets/images/product1.png'),        productId:1      },      {        productTitle:"KARMA",        image       : require('../assets/images/product2.png'),        productId:2      },      {        productTitle:"Tino",        image       : require('../assets/images/product3.png'),        productId:3      },      {        productTitle:"EFG",        image       : require('../assets/images/product4.png'),        productId:4      },      {        productTitle:"MLI",        image       : require('../assets/images/product5.png'),        productId:5      },      {        productTitle:"Banans",        image       : require('../assets/images/product6.png'),        productId:6      }      ]    }  }}

Then fetch and loop into the Products Array using the v-for directive .

然后使用v-for指令获取并循环进入Products Array。

<div class="row">      <div class="col-md-4 col-lg4" v-for="(data,index) in products" :key="index">        <img :src="data.image" class="img-fluid">         <h3>{{data.productTitle}}</h3>      </div>    </div>

The result:

结果:

To navigate to the details component, we first have to add a click event:

要导航到详细信息组件,我们首先必须添加一个click事件:

<h3 @click="goTodetail()" >{{data.productTitle}}</h3>

Then add methods:

然后添加方法:

methods:{  goTodetail() {    this.$router.push({name:'details'})  }

If you click the title, it will return undefined because we haven’t created the details component yet. So let’s create one:

如果单击标题,它将返回未定义的标题,因为我们尚未创建详细信息组件。 因此,让我们创建一个:

details.vue

details.vue

<template> <div class="details">  <div class="container">   <h1 class="text-primary text-center">{{title}}</h1>  </div> </div></template><script> export default{  name:'details',  data(){   return{    title:"details"   }  } }</script>

Now we can navigate without getting an error ?

现在我们可以导航而不会出错?

Now how can we browse to the details page and get the matched data if we don’t have a database?

现在,如果没有数据库,我们如何浏览到详细信息页面并获取匹配的数据?

We are going to use the same products array in the details component. So we can mach the id that comes from the URL:

我们将在details组件中使用相同的product数组。 因此,我们可以处理来自URL的ID:

products:[      {        productTitle:"ABCN",        image       : require('../assets/images/product1.png'),        productId:1      },      {        productTitle:"KARMA",        image       : require('../assets/images/product2.png'),        productId:2      },      {        productTitle:"Tino",        image       : require('../assets/images/product3.png'),        productId:3      },      {        productTitle:"EFG",        image       : require('../assets/images/product4.png'),        productId:4      },      {        productTitle:"MLI",        image       : require('../assets/images/product5.png'),        productId:5      },      {        productTitle:"Banans",        image       : require('../assets/images/product6.png'),        productId:6      }      ]

First we have to set the id to the goTodetail() method as a parameter:

首先,我们必须将id设置为goTodetail()方法作为参数:

<h3 @click="goTodetail(data.productId)" >{{data.productTitle}}</h3>

Then add a second parameter to the router method.

然后向路由器方法添加第二个参数。

The $router method takes two parameters: first, the name of the component we want to navigate to, and second, the id parameter (or any other parameter).

$router方法有两个参数:第一个是我们要导航到的组件的name ,第二个是id参数(或任何其他参数)。

this.$router.push({name:'details',params:{Pid:proId}})

Add Pid as the parameter in index.js inside the router folder:

router文件夹内的index.js中添加Pid作为参数:

{      path: '/details/:Pid',      name: 'details',      component: details    }

home.vue

methods:{  goTodetail(prodId) {    this.$router.push({name:'details',params:{Pid:proId}})  }  }

To get the matched parameter, use this line of code:

要获取匹配的参数,请使用以下代码行:

this.$route.params.Pid

details.vue

details.vue

<h2>the product id is :{{this.$route.params.Pid}}</h2>

Then loop through the products array in detalils.vue and check the object that matchs the parameter Pid and return its data:

然后遍历产品数组 detalils.vue并检查与参数Pid匹配的对象并返回其数据:

<div class="col-md-12" v-for="(product,index) in products" :key="index">     <div v-if="proId == product.productId">      <h1>{{product.productTitle}}</h1>      <img :src="product.image" class="img-fluid">     </div>    </div>
///export default{  name:'details',  data(){   return{    proId:this.$route.params.Pid,    title:"details"     }}

You see now that when we click any product’s link it get us to that product!

您现在看到的是,当我们单击任何产品的链接时,它将带我们到该产品!

detail.vue component:

detail.vue组件:

<template> <div class="details">  <div class="container">   <div class="row">    <div class="col-md-12" v-for="(product,index) in products" :key="index">     <div v-if="proId == product.productId">      <h1>{{product.productTitle}}</h1>      <img :src="product.image" class="img-fluid">     </div>    </div>   </div>  </div> </div></template><script> export default{  name:'details',  data(){   return{    proId:this.$route.params.Pid,    title:"details",    products:[    {    productTitle:"ABCN",    image       : require('../assets/images/product1.png'),    productId:1    },    {    productTitle:"KARMA",    image       : require('../assets/images/product2.png'),    productId:2    },    {    productTitle:"Tino",    image       : require('../assets/images/product3.png'),    productId:3    },    {    productTitle:"EFG",    image       : require('../assets/images/product4.png'),    productId:4    },    {    productTitle:"MLI",    image       : require('../assets/images/product5.png'),    productId:5    },    {    productTitle:"Banans",    image       : require('../assets/images/product6.png'),    productId:6    }    ]        }  } }</script>

过渡 (The transition)

In this part, we are going to add an animation transition to the animated component. We will animate the transition of the components. It makes the navigation awesome, and it creates a better UX and UI.

在这一部分中,我们将向动画组件添加动画过渡。 我们将为组件的过渡设置动画。 它使导航很棒,并且创建了更好的UX和UI。

To make an animation transition, put the “<router-view>” inside the “<transition/>” tag and give it a name of class.

要进行动画过渡,请将“ <router-view>”放在“ <transition />”标签内,并为其命名一个类。

App.vue

应用程序

<transition name="moveInUp">         <router-view/>  </transition>

To animate the transition of the component when it enters the view, add enter-active to the name given to the transition tag. Then add leave-active and then give it the CSS transition properties just like this:

要为组件进入视图时的过渡设置动画,请添加enter-active 赋予过渡标签的名称。 然后加 leave-active 然后为其提供CSS过渡属性,如下所示:

.moveInUp-enter-active{  opacity: 0;  transition: opacity 1s ease-in;}
使用CSS3动画 (Using CSS3 animation)

Now we are gonna animate using @keyframes in CSS3.

现在我们要在CSS3中使用@keyframes进行动画处理。

When the component enters the view, add a fade effect to the view.

当组件进入视图时,向视图添加淡入淡出效果。

.moveInUp-enter-active{  animation: fadeIn 1s ease-in;}@keyframes fadeIn{  0%{    opacity: 0;  }  50%{    opacity: 0.5;  }  100%{    opacity: 1;  }}

Add another fade effect when the component leaves the view.

当组件离开视图时,添加另一个淡入淡出效果。

Now we’re going to make the component move in and up when it leaves the view.

现在,我们将使组件在离开视图时上下移动。

.moveInUp-leave-active{  animation: moveInUp .3s ease-in;}@keyframes moveInUp{ 0%{  transform: translateY(0); }  100%{  transform: translateY(-400px); }}

Now you can create you own animations and transitions for your components.

现在,您可以为自己的组件创建自己的动画和过渡。

That’s it — we are done ! ?

就是这样-我们完成了! ?

You can Download the Source code here .

您可以在此处下载源代码

结语 (Wrapping up)

Routing in Vue.js makes your app pretty awesome when it come to navigation. It give it that energy of the single page web application, and it creates a better user experience.

Vue.js中的路由使您的应用在导航方面变得非常出色。 它使单页Web应用程序具有这种功能,并创造了更好的用户体验。

By the way…

顺便说说…

If you want to learn Bootstrap 4, check out my class on Skillshare with this referral link and get 2 free months access to 20,000 classes.

如果您想学习Bootstrap 4,请通过此推荐链接在Skillshare上查看我的课程,并获得2个月的免费访问时间,可访问20,000个课程。

Originally published on zeolearn.com

最初发布于zeolearn.com

Subscribe to this mailList to learn more about Front End topics, and Follow me on Twitter.

订阅此邮件列表,以了解有关前端主题的更多信息,并在Twitter上关注我。

By the way, I’ve recently worked with a strong group of software engineers for one of my mobile applications. The organization was great, and the product was delivered very quickly, much faster than other firms and freelancers I’ve worked with, and I think I can honestly recommend them for other projects out there. Shoot me an email if you want to get in touch — said@devsdata.com.

顺便说一句,我最近与一群强大的软件工程师一起为我的一个移动应用程序工作。 该组织很棒,产品交付速度非常快,比我所合作的其他公司和自由职业者要快得多,我想我可以诚实地向他们推荐其他项目。 如果您想与我联系,请给我发送电子邮件 -said@devsdata.com

翻译自: https://www.freecodecamp.org/news/how-to-use-routing-in-vue-js-to-create-a-better-user-experience-98d225bbcdd9/

vue.js中的路由

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值