vuejs 轮播_如何在VueJS中设计和构建轮播功能

vuejs 轮播

by Fabian Hinsenkamp

由Fabian Hinsenkamp设计

A carousel, slideshow, or slider — however you call it this class of UI — has become one of the core elements used in modern web development. Today, it’s almost impossible to find any Website or UI library which doesn’t come with one or another kind of carousel.

轮播,幻灯片或滑块(但是您将其称为此类UI)已成为现代Web开发中使用的核心元素之一。 如今,几乎找不到任何没有一种或另一种轮播的网站或UI库。

Why, though? In fact, carousels really deserve their popularity. They allow users to skim through available content without vertical scrolling or heavy mouse movements. Consequently, users save time and can focus on the displayed content as Carousels keep cognitive load to a minimum.

为什么呢? 实际上,轮播确实值得其流行。 它们使用户可以浏览可用内容,而无需垂直滚动或沉重的鼠标移动。 因此,用户可以节省时间并可以专注于显示的内容,因为轮播将认知负担降至最低。

This is reason enough to learn how to build a Carousel in VueJS!

这就是足够的理由来学习如何在VueJS中构建Carousel!

All my tutorials gravitate around Progressive Vue Apps. This one is no exception! Making progressive apps means delivering a UX for mobile users close to native apps, including excellent performance, native features like push notifications, offline experience and much more. In a world where the majority of users experience the Web via mobile devices, there is no excuse left to not build progressive apps!

我所有的教程都着重于Progressive Vue Apps。 这也不例外! 制作渐进式应用程序意味着向移动用户提供接近本机应用程序的UX,包括出色的性能,本机功能(如推送通知),离线体验等。 在大多数用户通过移动设备体验Web的世界中,没有理由不构建渐进式应用程序!

Of course you can still use the Carousel in any Vue app. You also don’t need any prior experience with VueJS or Progressive Web Apps for this tutorial!

当然,您仍然可以在任何Vue应用程序中使用“轮播”。 您也不需要任何使用VueJS或Progressive Web Apps的经验,就可以学习本教程!

You find the full code here:

您可以在此处找到完整的代码:

https://github.com/fh48/vue-pwa-carousel

https://github.com/fh48/vue-pwa-carousel

First thing we will do is to get an overview over what kind of components we want to build.

我们要做的第一件事是获得关于要构建哪种组件的概述。

There are a few very straightforward ones:

有一些非常简单的方法:

  • Card → it holds the information of each carousel element.

    →包含每个轮播元素的信息。

  • Carousel → parent which holds all logic

    轮播→拥有所有逻辑的父级

  • ArrowButton → helps to navigate between multiple cards.

    ArrowButton →帮助在多个卡之间导航。

  • Indicator → shows the number of cards and which is currently visible.

    指示器 →显示卡的数量,并且当前可见。

最初设定 (Initial Setup)

If you want to learn how to set up a project, this section is for you. In case you do not, just continue with the next section.

如果您想学习如何设置项目,本部分适合您。 如果您不这样做,请继续下一节。

vue init pwa vue-pwa-carousel

We will be prompted to pick a preset — I recommend the following configuration:

我们将提示您选择一个预设-我建议以下配置:

? Project name vue-pwa-carousel? Project short name: fewer than 12 characters to not be truncated on homescreens (default: same as name) vue-pwa-carousel? Project description A simple tax calculator ? Author Fabian Hinsenkamp? Vue build runtime? Install vue-router? No? Use ESLint to lint your code? No? Pick an ESLint preset Standard? Setup unit tests with Karma + Mocha? No? Setup e2e tests with Nightwatch? No

Run yarn in the root folder of the project to install all dependencies. Now we have a project set-up which includes the basic technologies we need to build our carousel. Moreover, it already includes a Service Worker which pre-caches all our static files and allows users to access the app even when they are offline.

在项目的根文件夹中运行yarn以安装所有依赖项。 现在,我们有一个项目设置,其中包括构建轮播所需的基本技术。 而且,它已经包括了一个Service Worker,它可以预先缓存我们所有的静态文件,并允许用户即使在脱机状态下也可以访问该应用程序。

You can check out how the template app looks like by running yarn start.

您可以通过运行yarn start来检查模板应用程序的外观。

To test how the carousel looks on mobile, we need to expose our development build to mobile devices through a public URL. There are many ways to do so, but here we use ngrok as it’s easy to set up and just does its job.

为了测试轮播在移动设备上的外观,我们需要通过公共URL将开发版本暴露给移动设备。 这样做有很多方法,但是这里我们使用ngrok因为它很容易设置并且可以正常工作。

yarn global add ngrok

Next, we need to run our dev server and ngrok in two separate terminals.

接下来,我们需要在两个单独的终端中运行开发服务器和ngrok。

让我们来制作卡片! (Let’s build the Card!)

To save you some boring adjustments to the template app, just check out this branch00_basicSetup. It includes all data and styles we need to make this app meaningful and pretty.

为了节省对模板应用程序的无聊调整,只需签出该分支00_basicSetup 。 它包含使该应用程序有意义且美观所需的所有数据和样式。

The Card really does one thing: it shows the currently selected data. Which is, in our case, an image, a headline and some text.

该卡确实做一件事:它显示当前选择的数据。 在我们的例子中,它是图像标题和一些文本

Clearly, we do not want to build multiple cards with hard-coded content. Instead, we want to dynamically pass the data to the card and simply render it.

显然,我们不想用硬编码内容构建多张卡。 取而代之的是,我们希望将数据动态传递到卡上并简单地呈现它。

Based on that knowledge, we can now create our Card.vue file in the src/components folder. Moreover, we can already define the basic html structure and names and their types of the properties we want to pass to the card.

基于此知识,我们现在可以在src/components文件夹中创建Card.vue文件。 而且,我们已经可以定义基本的html结构和名称以及它们要传递给卡的属性的类型。

Attention: we store all icons we want to display locally in our assets folder. That means that our path remains the same, but we need to dynamically change the file names which are supposed to be rendered. Consequently, all properties are of type String.

注意:我们会将要显示在本地的所有图标存储在资产文件夹中。 这意味着我们的路径保持不变,但是我们需要动态更改应该呈现的文件名。 因此,所有属性均为String类型。

Next, we make the Card render the headline and the related text. Therefore, we use the most basic way of data-binding within VueJS — the mustache tag.

接下来,我们使卡片呈现标题和相关文本。 因此,我们在VueJS中使用最基本的数据绑定方式-mustache标签。

It’s basically just curly braces around our prop variables. As soon as data comes in, {{headline}} and {{text}} will be replace with the related data object. This is always true, also when new data comes in, after is has rendered other data before.

基本上,我们的prop变量只是花括号。 数据一输入, {{headline}}{{text}}将被相关的数据对象替换。 在输入新数据之后,之前已渲染其他数据之后,也总是如此。

Rendering the image dynamically is a bit more tricky. Remember, we do not pass the actual icon but only its file name.

动态渲染图像有些棘手。 请记住,我们不传递实际图标,而仅传递其文件名。

So we basically want to consume the image as a module, like any other component. A static image we could consume by importing it in the script block and assign it to a variable. However, we do have changing path. As our app uses webpack there is a fantastic shorthand available to load these dynamically as follows:

因此,我们基本上希望像其他任何组件一样将图像作为模块使用。 我们可以通过将静态图像导入脚本块并将其分配给变量来使用它。 但是,我们确实有改变的道路。 当我们的应用程序使用webpack时,可以使用一个很棒的速记来动态加载它们,如下所示:

:src="require(`@/assets/svg/${imgName}`)"

The : syntax is the Vue-way to dynamically bind attributes to an expression. You might already have seen the v-bind: prefix which : is the shorthand for.

:语法是将属性动态绑定到表达式的Vue方法。 您可能已经看过v-bind:前缀,它是:的简写。

Now our template block is completed and looks as follows.

现在,我们的template板块已完成,如下所示。

To finalise our Card component, we simply need to add the prepared styled to the bottom of the file.

要完成我们的Card组件,我们只需要在文件底部添加准备好的样式即可。

<style src="../assets/styles/Card.css" scoped>

Last thing we need to do for this section is to check if the Card actually works.

我们在本节中要做的最后一件事是检查卡是否真正起作用。

So let’s simply add it the our App.vue component. However, keep in mind that we will have to move the component into the Carousel component in the next section.

因此,我们只需将其添加到我们的App.vue组件中即可。 但是,请记住,在下一节中,我们将不得不将组件移至“ 旋转木马”组件中。

We add the following to the <template>; and &lt;script>; blocks of App.vue.

我们将以下内容添加到<templa te>中; and &l ; and &l t; script> ; block App.vue的s ; block

What a fantastic result! Especially, since we can already dynamically change whatever the Card should display!

太棒了! 特别是,由于我们已经可以动态更改应显示的内容!

Next, we build the Carousel to have a dedicated component to manage all logic around showing different Cards based on user inputs.

接下来,我们将构建轮播,使其具有专用组件,以根据用户输入来管理显示不同的所有逻辑。

Check out the branch 01_Card to if you want to start from here or compare your implementation.

如果要从这里开始,请检查分支01_Card或比较您的实现。

The Carousel will be our reusable parent component. It will encapsulate all relevant components and logic.

轮播将是我们可重用的父组件。 它将封装所有相关的组件和逻辑。

Like with the Card before, we should focus on building the component in a way that it can handle a change in data gracefully. For example, it should be capable of handling varying numbers of cards being passed to it.

像以前的Card一样,我们应该集中精力以一种可以优雅地处理数据更改的方式来构建组件。 例如,它应该能够处理传递给它的不同数量的卡。

Next we will see how this approach translates into Code. First we start with creating a Carousel component and make the Card a child of Carousel.

接下来,我们将看到这种方法如何转换为代码。 首先,我们首先创建一个Carousel组件,然后将Card作为Carousel的子代。

The template block of the new component hosts the Card, wrapped in two wrapper elements. We will see later why these are necessary.

新组件的模板块托管Card ,并包装在两个包装器元素中。 我们将在后面看到为什么这些必要。

As we will pass data of multiple Cards to the Carousel, we need to specify that only the currentElement is rendered.

当我们将多个Card的数据传递到Carousel时,我们需要指定仅呈现currentElement

In the following <script> block we need to define which of the passed Cards is the currentElement by default.

在下面的<scri pt>块中,我们需要定义默认情况下,哪些传递的卡s the currentE元素。

Therefore, we define the currentElementIndex initially to be 0. VueJS comes with a feature that allows us to compute variables dynamically. We use it to select the data of the card that should render initially.

因此,我们将currentElementIndex初始定义为0 。 VueJS带有一项功能,使我们能够动态计算变量。 我们使用它来选择最初应呈现的卡的数据。

Now we only need to replace the Card with the Carousel in our App.vue file. To put a bit more structure and meaning to our final page, let’s wrap the carousel in another section element and place it before the other section.

现在,我们只需要更换我们与旋转木马 App.vue文件。 为了使我们的最后一页更具结构性和意义,让我们将轮播包装到另一个section元素中,然后将其放置在另一个section之前。

That’s our basic implementation. It is not quite a Carousel yet but we are about to change this by adding the arrow buttons to switch between the objects we pass in the cards array to our Carousel.

那是我们的基本实现。 它还不是旋转木马,但我们将通过添加箭头按钮来更改此设置,以在我们将cards数组传递给旋转木马的对象之间进行切换。

Check out the 02_Carousel to see the complete code for this section. If you coded along you should see the following in front of you.

查看02_Carousel以查看此部分的完整代码。 如果您沿代码进行编码,则应该在您前面看到以下内容。

让我们来构建ArrowButton (Let’s build the ArrowButton)

Now we build the ArrowButton component, which receives its methods and the type of arrow icon from its parent. The implementation itself is strait forward.

现在,我们构建ArrowButton组件,该组件从其父级接收其方法和箭头图标的类型。 实现本身是两难的。

The component is only responsible for rendering the correct styles and the icon. All logic related to the Buttons is added to the Carousel. That way, we have created a truly generic component we could use in any context where we want to use a button with an arrow icon.

该组件仅负责呈现正确的样式和图标。 与按钮相关的所有逻辑均已添加到轮播中。 这样,我们创建了一个真正通用的组件,可以在要使用带有箭头图标的按钮的任何上下文中使用。

Now, within Carousel, we add two methods to navigate between our card data objects. Methods are just another exported object within the <script> block.

现在,在Carousel中,我们添加了两种方法来在卡片数据对象之间导航。 方法只是<scri pt>块中的另一个导出对象。

These simply increase or decrease the currentElementIndex by 1. We use the index to compute the currentElement variable, so every time one of the methods is called the next card is displayed. We also add some restrictive conditions, as we want the Carousel not to loop.

这些只是将currentElementIndex增加或减少1 。 我们使用索引来计算currentElement变量,因此每次调用其中一个方法时,都会显示下一张卡片。 我们还添加了一些限制性条件,因为我们希望轮播不循环。

Now we only need to add the ArrowButtons to basically complete our Carousel!

现在我们只需要添加ArrowButtons即可基本完成我们的轮播

Here you see how we use the methods and computed values to implement one of our ArrowButtons. Try to implement the second one below the Card component.

在这里,您将看到我们如何使用方法和计算值来实现我们的ArrowButtons之一 。 尝试在Card组件下实施第二个组件。

In case you get stuck or something just looks wrong, checkout the 03_ArrowButton branch. If everything worked out though, your carousel should look like the following:

万一卡住或看起来有些不对劲,请检查03_ArrowButton分支。 如果一切顺利,您的轮播应如下所示:

让我们建立指标! (Let’s build Indicators!)

The last feature we’re going to add are the Indicators. These help users to understand how many Cards there are and which one they are currently looking at. Additionally, these allow the user to select individual Cards directly.

我们要添加的最后一个功能是指标。 这些可以帮助用户了解有多少张卡以及他们当前正在看哪张卡。 另外,这些允许用户直接选择单个卡。

The component receives three properties. The array of elements we use to create a <li> element for each card data object.

该组件接收三个属性。 elements数组 我们用于为每个卡数据对象创建一个< l i>元素。

currentElementIndex is required to add a CSS class that highlights the indicator related to the current card. Moreover, it is used to disable the button for the current card. That way we prevent it from being selectable is via the tab keys. That way, we provide at least a minimum of accessibility.

currentElementIndex 需要添加一个CSS类来突出显示与当前卡有关的指示器。 此外,它用于禁用当前卡的按钮。 这样,我们可以通过Tab键阻止它被选择。 这样,我们至少提供了最少的可访问性。

showElement is the method which is called when a user clicks on an indicator. It’s passed from outside to keep the component as focused as possible. How an element is shown is clearly no concern of Indicators.

showElement是用户单击指标时调用的方法。 它是从外部传递的,以使组件尽可能集中。 元素的显示方式显然与指标无关。

When we add the Indicators to Carousel.vue it becomes clear why we created two wrappers for the Card. Semantic and clear HTML is vital, especially for large projects with a high level of complexity.

当我们将指标添加到Carousel.vue很清楚为什么我们为Card创建了两个包装 语义清晰HTML至关重要,特别是对于具有高度复杂性的大型项目而言。

You can check out the complete code at branch 04_Indicators.

您可以在分支04_Indicators04_Indicators完整的代码。

让我们添加滑动 (Let’s add swipe)

Last but not least, we make our Carousel mobile friendly. A good progressive web app doesn’t start by caching static files, but with responsiveness.

最后但并非最不重要的一点是,我们使Carousel移动友好。 一个好的渐进式Web应用程序并非从缓存静态文件开始,而是具有响应能力。

As we do lack space on small screens, we hide the ArrowButtons and allow users to swipe in order to browse the Cards. Here the Indicators also do pay off again, as they function in mobile as the main indicator that users can swipe to see more cards.

由于我们确实在小屏幕上缺少空间,因此我们隐藏了ArrowButtons并允许用户滑动以浏览Cards。 此处,指示器也可以再次获得回报,因为它们在移动设备中充当主要指示器,用户可以滑动以查看更多卡。

Therefore we add the following library:

因此,我们添加以下库:

yarn add vue2-touch-events

Next we add the new v-touch attribute and a handler method to the Card. This takes care of the events emitted by swipes.

接下来,我们向Card添加新的v-touch属性和处理程序方法 这可以照顾到刷卡发出的事件。

结论 (Conclusion)

Fantastic, we made it! We had the vision of building an encapsulated and reusable Carousel component, and we did!

太棒了,我们做到了! 我们的愿景是构建一个封装的和可重复使用的Carousel组件,我们做到了!

What we still could add to improve the UX are some swipe animation when browsing the cards.

浏览卡片时,我们仍然可以添加一些改进滑动效果的动画。

Thanks for reading! If you like this blog post, Follow me on Twitter @Fa_Hinse and please clap?

谢谢阅读! 如果您喜欢此博客文章, 在Twitter @Fa_Hinse上关注我, 请鼓掌吗?

翻译自: https://www.freecodecamp.org/news/how-to-design-and-build-a-carousel-feature-in-vuejs-125f690a3a9e/

vuejs 轮播

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/392091.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

iOS绘圆形图-CGContextAddArc各参数说明

2019独角兽企业重金招聘Python工程师标准>>> 1.使用 UIGraphicsGetCurrentContext() 画圆 CGContextAddArc(<#CGContextRef _Nullable c#>, <#CGFloat x#>, <#CGFloat y#>, <#CGFloat radius#>, <#CGFloat startAngle#>, <#CGFlo…

c语言中if和goto的用法,C语言中if和goto的用法.doc

C语言中if和goto的用法C语言中&#xff0c;if是一个条件语句&#xff0c;用法??if(条件表达式) 语句如果满足括号里面表达式&#xff0c;表示逻辑为真于是执行后面的语句&#xff0c;否则不执行(表达式为真则此表达式的值不为0&#xff0c;为假则为0&#xff0c;也就是说&…

数据挖掘—K-Means算法(Java实现)

算法描述 &#xff08;1&#xff09;任意选择k个数据对象作为初始聚类中心 &#xff08;2&#xff09;根据簇中对象的平均值&#xff0c;将每个对象赋给最类似的簇 &#xff08;3&#xff09;更新簇的平均值&#xff0c;即计算每个对象簇中对象的平均值 &#xff08;4&#xf…

自我价值感缺失的表现_不同类型的缺失价值观和应对方法

自我价值感缺失的表现Before handling the missing values, we must know what all possible types of it exists in the data science world. Basically there are 3 types to be found everywhere on the web, but in some of the core research papers there is one more ty…

[收藏转载]C# GDI+ 简单绘图(一)

最近对GDI这个东西接触的比较多&#xff0c;也做了些简单的实例&#xff0c;比如绘图板&#xff0c;仿QQ截图等&#xff0e; 废话不多说了&#xff0c;我们先来认识一下这个GDI&#xff0c;看看它到底长什么样. GDI&#xff1a;Graphics Device Interface Plus也就是图形设备接…

mybaties总结+hibernate总结

一、对原生态jdbc程序中问题总结 1.1 jdbc程序 需求&#xff1a;使用jdbc查询mysql数据库中用户表的记录 statement:向数据库中发送一个sql语句 预编译statement&#xff1a;好处&#xff1a;提高数据库性能。 预编译statement向数据库中发送一个sql语句&#xff0c;数据库编译…

客户旅程_我如何充分利用freeCodeCamp的旅程

客户旅程by Catherine Vassant (aka Codingk8)由凯瑟琳瓦森(Catherine Vassant)(又名Codingk8) 我如何充分利用freeCodeCamp的旅程 (How I made the most out of my freeCodeCamp journey) 我的路线图&#xff1f; ️超越课程范围的reeCodeCamp (My road map ?️ to freeCode…

Python14 函数

函数 面向对象编程&#xff1a; 类----class 面向过程编程&#xff1a;过程---def 函数式编程&#xff1a;函数---def def test(x):描述x 1return x#def是定义函数的关键字#test是函数名称#&#xff08;x&#xff09;是参数#x1是 函数体&#xff0c;是一段逻辑代码#return 定义…

学习sql注入:猜测数据库_面向数据科学家SQL:学习简单方法

学习sql注入:猜测数据库We don’t pick a hammer and look for nails — that would be an unusual way of solving problems. The usual way of doing business is to identify the problem first, then look for appropriate tools.我们不用锤子找钉子&#xff0c;那是解决问…

android 百度地图3.0,android 百度地图3.0

一&#xff1a;为地图设置事件注意新版本中要有一个getMapmMapView.getMap().setOnMapStatusChangeListener(listener);OnMapStatusChangeListener listener newOnMapStatusChangeListener() {/*** 手势操作地图&#xff0c;设置地图状态等操作导致地图状态开始改变。* param s…

(摘录)sockaddr与sockaddr_in,sockaddr_un结构体详细讲解

struct sockaddr { unsigned short sa_family; /* address family, AF_xxx */ char sa_data[14]; /* 14 bytes of protocol address */ }; sa_family是地址家族&#xff0c;一般都是“AF_xxx”的形式。好像通常大多用的是都是AF_INET。 sa_data是14字节协议…

数据挖掘—K-中心点聚类算法(Java实现)

K-中心点聚类算法 &#xff08;1&#xff09;任意选择k个对象作为初始的簇中心点 &#xff08;2&#xff09;指派每个剩余对象给离他最近的中心点所表示的簇 &#xff08;3&#xff09;选择一个未被选择的中心点直到所有的中心点都被选择过 &#xff08;4&#xff09;选择一个…

使用akka构建高并发程序_如何使用Akka Cluster创建简单的应用程序

使用akka构建高并发程序If you read my previous story about Scalachain, you probably noticed that it is far from being a distributed system. It lacks all the features to properly work with other nodes. Add to it that a blockchain composed by a single node is…

pandas之数值计算与统计

数值计算与统计 对于DataFrame来说&#xff0c;求和、最大、最小、平均等统计方法&#xff0c;默认是按列进行统计&#xff0c;即axis 0&#xff0c;如果添加参数axis 1则会按照行进行统计。 如果存在空值&#xff0c;在统计时默认会忽略空值&#xff0c;如果添加参数skipna …

python自动化数据报告_如何:使用Python将实时数据自动化到您的网站

python自动化数据报告This tutorial will be helpful for people who have a website that hosts live data on a cloud service but are unsure how to completely automate the updating of the live data so the website becomes hassle free. For example: I host a websit…

一颗站在技术边缘的土豆

2012年开始上专业课&#xff0c;2013年打了一年游戏&#xff0c;年底专业课忘光了&#xff0c;但是蒙混过关没挂科&#xff0c;2014年7月份毕业&#xff0c;对这个社会充满向往。2014年9月份——方正代理商做网络安全公司。2015年3月份跳槽到一家vmware代理商公司。2016年6月&a…

leetcode 839. 相似字符串组(并查集)

如果交换字符串 X 中的两个不同位置的字母&#xff0c;使得它和字符串 Y 相等&#xff0c;那么称 X 和 Y 两个字符串相似。如果这两个字符串本身是相等的&#xff0c;那它们也是相似的。 例如&#xff0c;“tars” 和 “rats” 是相似的 (交换 0 与 2 的位置)&#xff1b; “r…

android intent参数是上次的结果,【Android】7.0 Intent向下一个活动传递数据、返回数据给上一个活动...

1.0 可以利用Intent吧数据传递给上一个活动&#xff0c;新建一个叫“hellotest01”的项目。新建活动FirstActivity&#xff0c;勾选“Generate Layout File”和“Launcher Activity”。image修改AndroidMainifest.xml中的内容&#xff1a;android:name".FirstActivity&quo…

实习一年算工作一年吗?_经过一年的努力,我如何找到软件工程工作

实习一年算工作一年吗?by Andrew Ngo通过安德鲁恩戈 经过一年的努力&#xff0c;我如何找到软件工程工作 (How I landed a software engineering job after a year of hard work) Many of us think the path to becoming a software engineer requires years of education an…

学习深度学习需要哪些知识_您想了解的有关深度学习的所有知识

学习深度学习需要哪些知识有关深层学习的FAU讲义 (FAU LECTURE NOTES ON DEEP LEARNING) Corona was a huge challenge for many of us and affected our lives in a variety of ways. I have been teaching a class on Deep Learning at Friedrich-Alexander-University Erlan…