alpine 交互sh
Alpine.js is a rugged, minimal framework for composing Javascript behavior in your markup. That's right, in your markup!
Alpine.js是一个坚固的最小框架,用于在标记中构成Javascript行为。 是的,在您的标记中!
It allows you to write most of your JS inline in your HTML, making it easier to write declarative code (as opposed to procedural code). According to its creator Caleb Porzio, it aims to fill the void between vanilla JS (or jQuery) and large v-dom frameworks like Vue/React.
它使您可以在HTML中内联编写大部分JS内联代码,从而使编写声明性代码(相对于过程代码)更加容易。 根据其创建者Caleb Porzio的说法,它旨在填补香草JS(或jQuery)与大型v-dom框架(如Vue / React)之间的空白。
We at Scrimba definitely think it lives up to its promise, so we're happy to present you with a free one-hour course!
我们在斯克林巴(Scrimba)肯定认为它兑现了诺言,因此很高兴为您提供免费的一小时课程!
In it, you'll find a bunch of fun and interactive tutorials which embed your learning and give you the muscle memory you need to become a hotshot at Alpine.js.
在其中,您将找到很多有趣的交互式教程,这些教程可以使您深入学习,并获得成为Alpine.js热门人物所需的肌肉记忆。
Now let's have a look at how the course is structured!
现在让我们看一下课程的结构!
为什么要学习Alpine.js? (Why learn Alpine.js?)
In the first lesson, the teacher Andre Madarang starts off by explaining why you should learn the library. Shortly speaking, Alpine.js works well when you need a small amount of JS, e.g. a few drop-downs or tabs. This means you get a bunch of power at a crazy small size with no need to NPM install.
在第一课中,老师Andre Madarang首先说明了您为什么要学习图书馆。 简而言之,当您需要少量JS(例如,一些下拉菜单或选项卡)时,Alpine.js会很好地工作。 这意味着您可以以疯狂的小尺寸获得大量功能,而无需安装NPM。
Andre also gives you an introduction to himself. He is a full-stack developer and Youtuber who teaches web development concepts such as Laravel, Vue and Tailwind CSS. We're thrilled to have him onboard as a Scrimba teacher!
安德烈(Andre)还向您介绍了自己。 他是一名全栈开发人员和Youtuber,教过Web开发概念,例如Laravel,Vue和Tailwind CSS。 我们很高兴让他加入Scrimba老师!
安装和基本的阿尔卑斯组件 (Installation & A Basic Alpine Component)
Installing Alpine.js is easy - you can use npm if you want, but Andre also shows us how to use a cdn and add it in a script
tag - it's as simple as that!:
安装Alpine.js很容易-如果需要,您可以使用npm,但是Andre还向我们展示了如何使用cdn并将其添加到script
标签中-就是这么简单!
<head>
<script
src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v1.9.8/dist/alpine.js"
defer
></script>
</head>
Now, it's time to create our first Alpine.js component! First, we define state using the x-data
attribute. State is available within the scope of the <div>
in which it is defined, so in the example below, both the <button>
and the <h1>
have access to state.
现在,该创建我们的第一个Alpine.js组件了! 首先,我们使用x-data
属性定义状态。 状态在定义它的<div>
范围内可用,因此在下面的示例中, <button>
和<h1>
都可以访问状态。
To use this state, we then use the x-show
directive to show or hide the element and toggle the element on and off using @
.
要使用此状态,我们然后使用x-show
指令显示或隐藏元素,并使用@
启用和禁用该元素。
<div x-data="{ isOpen: true }">
<button @click=" isOpen = !isOpen">Toggle</button>
<h1 x-show="isOpen">index.html</h1>
</div>
落下 (Dropdown)
Now, we use our new-found knowledge of state to implement a dropdown.
现在,我们使用新发现的状态知识来实现下拉菜单。
We then see how to set events to close the dropdown by clicking off the dropdown or by pressing the escape key, using @click.away
on the <ul>
or @keydown.escape
on the <button>
.
然后,我们看看如何设置事件通过单击关闭下拉关闭下拉或按ESC键,使用@click.away
在<ul>
或@keydown.escape
在<button>
。
模态和外部参照 (Modals and x-ref)
In this cast, Andre takes us through another example of how to use state to open and close a modal. Next, he introduces references, which allow us to add methods to particular elements in the click handler.
在此演员表中,安德烈(Andre)为我们介绍了如何使用状态打开和关闭模式的另一个示例。 接下来,他介绍了一些引用,这些引用使我们可以向点击处理程序中的特定元素添加方法。
In this case, we focus the close button once the modal is open by adding a reference to the close button with an x-ref
directive and then adding a method to the click handler.
在这种情况下,一旦模式打开,我们就通过将关闭引用添加到带有x-ref
指令的关闭按钮上,然后将方法添加到点击处理程序中,来对关闭按钮进行聚焦。
<button
class="bg-blue-700 text-white px-4 py-3 mt-4 text-sm rounded"
@click="isOpen = false"
x-ref="modalCloseButton"
></button>
<button
class="bg-blue-700 text-white px-4 py-3 mt-4 text-sm rounded"
@click="isOpen = true
$nextTick(() => $refs.modalCloseButton.focus())
"
></button>
侧边栏 (Sidebar)
Now it's time for some revision to help our new knowledge sink in. In this short cast, we add the functionality to toggle the visibility of a sidebar. This is a great way of embedding our learning and shows us another application of what we have learned.
现在是时候进行一些修订以帮助我们吸收新知识了。在此简短的介绍中,我们添加了功能以切换边栏的可见性。 这是嵌入我们的学习的一种好方法,并向我们展示了所学知识的另一种应用。
标签 (Tabs)
Next up, we build a set of tabs. This is more involved than our previous examples because we have to hold state for all the tabs, not just a boolean.
接下来,我们构建一组选项卡。 这比之前的示例更加复杂,因为我们必须保持所有选项卡的状态,而不仅仅是布尔值。
As usual, state is defined using the x-data
directive on an HTML element which encapsulates all the required elements. We then set the default to tab1
and set an event listener (which makes the tab active) for each one of the tabs.
通常,状态是在封装了所有必需元素HTML元素上使用x-data
指令定义的。 然后,我们将默认值设置为tab1
并为每个选项卡设置一个事件侦听器(使该选项卡处于活动状态)。
<li class="-mb-px mr-1">
<a
class="inline-block rounded-t py-2 px-4 font-semibold hover:text-blue-800 bg-white text-blue-700 border-l border-t border-r"
href="#"
@click.prevent="tab = 'tab1'"
>Tab 1</a
>
</li>
To change the contents section to the contents of the tab which has been clicked, we add x-show
directives to the <div>s
containing the contents:
要将内容部分更改为已单击的选项卡的内容,我们将x-show
指令添加到包含内容的<div>s
中:
<div x-show="tab === 'tab1'"></div>
Finally, Andre shows us how to apply the active tab styles with conditional class rendering.
最后,Andre向我们展示了如何在条件类渲染中应用活动选项卡样式。
:class="{ 'bg-white text-blue-700 border-l border-t border-r' : tab === 'tab1'
}" ;
影像选择 (Image Selection)
In this cast, Andre shows us how the skills we learned in the previous cast can be applied to a different UI experience - an image selector. Image selectors work in the same way as tabs, but with images instead of text.
在本演员表中,Andre向我们展示了如何将在上一个演员表中学到的技能应用于另一种UI体验-图像选择器。 图像选择器的工作方式与标签相同,但图像而不是文本。
滚动检测 (Scroll Detection)
Now, Andre shows us how to build a scroll detector which changes the background color as the user scrolls. To do this, we define some state which keeps track of whether the user has scrolled.
现在,Andre向我们展示了如何构建一个滚动检测器,该检测器会随着用户滚动而改变背景色。 为此,我们定义一些状态来跟踪用户是否滚动。
<div x-data="{ atTop: true }"></div>
Now, we add a scroll event listener on the window and some conditional class rendering on the <nav>
.
现在,我们在窗口上添加一个滚动事件侦听器,并在<nav>
上添加一些条件类渲染。
<nav
class="p-4 w-full fixed"
:class="{ 'bg-white shadow-md' : !atTop }"
@scroll.window="atTop = (window.pageYOffset > 40) ? false : true"
>
Top Nav goes here
</nav>
手风琴切换和循环 (Accordion Toggle and Loops)
In this section, we build an accordion toggle using loops. In our example, there are several FAQs with answers, and we want to toggle the visibility of the answers.
在本节中,我们使用循环构建一个手风琴切换。 在我们的示例中,有一些带有答案的FAQ,我们希望切换答案的可见性。
A great way of doing this without repeating code is to use loops. To do this, we store all our questions and answers in an array, loop over them, and then set the event listener on each iteration of the loop.
无需重复执行代码的一种好方法是使用循环。 为此,我们将所有问题和答案存储在一个数组中,对其进行循环,然后在循环的每次迭代中设置事件侦听器。
Note: For this to work, our elements need to be wrapped in a template
tag.
注意:要使此方法起作用,我们的元素需要包装在template
标签中。
<template x-for="faq in faqs" :key="faq.question">
<div>
<button
class="w-full font-bold border-b border-gray-400 py-3 flex justify-between items-center mt-4"
@click="faq.isOpen = !faq.isOpen"
>
<div x-text="faq.question"></div>
</button>
<div
class="text-gray-700 text-sm mt-2"
x-text="faq.answer"
x-show="faq.isOpen"
></div>
</div>
</template>
提取并x-init (fetch and x-init)
Now, we see how we can make requests to an external API. This sounds intimidating but is easily broken down into four steps.
现在,我们了解如何向外部API发出请求。 这听起来很吓人,但很容易分解为四个步骤。
- Add state to hold the quotes: 添加状态以保留引号:
x - data = "{ quote:'' }";
- Give the app a quote to show upon initialization: 给应用报价以在初始化时显示:
x - init = "quote = 'Awesome quote'";
Set the text in the
<div>
which displays the quote as the state:在
<div>
设置文本,将报价显示为状态:
Use fetch
to grab the quote from an external API:
使用fetch
从外部API获取报价:
x-init=" fetch('https://api.kanye.rest') .then(response => response.json()) .then(data => quote = data.quote) "
Here's the full code block:
这是完整的代码块:
<div
class="container mx-auto px-4"
x-data="{ quote:'' }"
x-init="
fetch('https://api.kanye.rest')
.then(response => response.json())
.then(data => quote = data.quote)
"
>
<div
class="flex items-center text-center justify-center h-screen text-2xl italic"
x-text='`"${quote}"`'
></div>
</div>
The UI looks like this:
用户界面如下所示:
Todo App和X模型 (Todo App and x-model)
In this cast, we learn how to build a mini to-do app. We need three pieces of state for this; one for keeping the to-dos in an array (todos
), one to keep track of whether the user types in a new to-do (todoTitle
) and one to keep track of the new to-do ID (todoId
).
在此演员表中,我们将学习如何构建迷你待办应用程序。 为此,我们需要三个状态。 一种用于将待办事项保持在一个数组中( todos
),一种用于跟踪用户是否键入新的待办事项( todoTitle
),一种用于跟踪新的待办事项ID( todoId
)。
As we are using many pieces of state, we extract our function to a <script>
tag to make things cleaner. The function returns an object which contains our state and our functions:
当我们使用许多状态时,我们将函数提取到<script>
标记中,以使事情更整洁。 该函数返回一个包含我们的状态和函数的对象:
<script>
function todos() {
return {
todos: [
{
id: 1,
title: "Finish Alpine Screencast",
isComplete: false
}
],
todoTitle: "",
todoId: 2
};
}
</script>
Now we loop over our to-dos to display the title we have stored in the array and conditionally add a line-through if the to-do is completed.
现在,我们遍历待办事项以显示已存储在数组中的标题,并在待办事项完成后有条件地添加一行。
<template x-for="todo in todos" :key="todo.id">
<li class="flex items-center justify-between">
<div
class="flex items-center"
:class="{ 'line-through' : todo.isComplete }"
>
<input type="checkbox" />
<div class="ml-3" x-text="todo.title"></div>
</div>
<button class="text-xl ml-2">×</button>
</li>
</template>
We now work on adding a to-do. First, we add an x-model
directive to our <input>
which syncs the todoTitle
with whatever is typed into the <input>
:
现在,我们要添加待办事项。 首先,我们添加一个x-model
指导我们<input>
它同步的todoTitle
与任何键入到<input>
:
<input
type="text"
class="shadow w-full px-2 py-2"
x-model="todoTitle"
@keydown.enter="addTodo()"
/>
The function we want to run when a user types a new to-do is then added to our <script>
tag.
然后,当用户键入新的待办事项时,我们要运行的功能将添加到我们的<script>
标记中。
We also use an x-model
on the checkbox to allow the user to mark a to-do as complete.
我们还在复选框上使用了x-model
,以允许用户将待办事项标记为已完成。
<input type="checkbox" x-model="todo.isComplete" />
过渡:下拉菜单 (Transitions: Dropdown)
Next up, Andre shows us some funky transitions which give our dropdown a crisp and professional finish using Tailwind CSS utility classes. These transitions give you fine-grained control over how your dropdown switches from hidden to visible, with options including opacity, duration, origin and others.
接下来,Andre向我们展示了一些时髦的过渡,这些过渡使用Tailwind CSS实用工具类为下拉菜单提供了清晰,专业的效果。 通过这些过渡,您可以对下拉菜单从隐藏状态切换为可见状态的方式进行细粒度的控制,其中包括不透明度,持续时间,来源和其他选项。
<ul
x-show="isOpen"
@click.away="isOpen = false"
class="absolute font-normal bg-white shadow overflow-hidden rounded w-48 border mt-2 py-1 right-0 z-20"
x-transition:enter="transition transform origin-top-right ease-out duration-200"
x-transition:enter-start="opacity-0 scale-75"
x-transition:enter-end="opacity-100 scale-100"
x-transition:leave="transition transform origin-top-right ease-out duration-200"
x-transition:leave-start="opacity-100 scale-100"
x-transition:leave-end="opacity-0 scale-75"
></ul>
过渡:模态 (Transitions: Modal)
Now it's time to put our new knowledge of transitions to the test by adding them to our modal. In the spirit of Scrimba, Andre gives us a chance to test out our new skills before showing us how he does it, so no spoilers here!
现在是时候通过将过渡的新知识添加到测试模型中来对其进行测试了。 本着Scrimba的精神,安德烈(Andre)让我们有机会在向我们展示他如何做之前测试我们的新技能,因此这里没有破坏者!
过渡:边栏 (Transitions: Sidebar)
Finally, we add a nice, smooth transition for the sidebar we implemented earlier. Again, no spoilers, so you can go ahead and give it shot yourself when you watch the course.
最后,我们为之前实现的边栏添加了一个很好的平滑过渡。 再次,没有破坏者,因此您可以继续前进,并在观看课程时亲自拍摄。
结论 (Conclusion)
We've now taken a look at some use cases for Alpine.js and built a few examples where it might be a better choice than React or Vue. Hopefully you've learned something new about Alpine.js and will be putting your new skills to good use very soon.
现在,我们研究了Alpine.js的一些用例,并构建了一些示例,这些示例可能比React或Vue更好。 希望您学到了有关Alpine.js的新知识,并将很快将您的新技能投入使用。
If you haven't already, don't forget to check out the course over at Scrimba.
如果您还没有这样做,请不要忘记在Scrimba上检查课程 。
In the meantime, happy Alpine coding! :)
同时,祝您Alpine编码愉快! :)
翻译自: https://www.freecodecamp.org/news/learn-alpine-js-in-this-free-tutorial-course/
alpine 交互sh