一篇文章Stimulus:连接HTML和JavaScript的桥梁,实现简单的controller,并学习了Stimulus是如何连接HTML与JavaScript的。现在我们使用Stimulus来实现复制文本到粘贴板的按钮。
比如说,我们现在有一个需求,就是帮助用户生成密码,在密码旁边放置一个按钮,点击按钮后密码就被拷贝到粘贴板上了,这样就方便用户使用这个密码了。
打开public/index.html,修改body内容,填充一个简单的按钮,如下:
<div>
PIN: <input type="text" value="1234" readonly>
<button>Copy to Clipboard</button>
</div>
下一步,创建src/controllers/clipboard_controller.js,然后添加一个copy()方法:
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
copy() {
}
}
然后,给div添加data-controller=“clipboard”。只要是给元素添加了data-controller属性,Stimulus就会连接一个controller实例。
<div data-controller="clipboard">
我们还需要一个对输入框的引用,这样我们就可以在调用粘贴板API之前获取输入框的内容。给文本框添加data-clipboard-target=“source“:
PIN: <input data-clipboard-target="source" type="text" value="1234" readonly>
在controller中定义一个target,然后就可以通过this.sourceTarget访问文本框了。
import { Controller } from "@hotwired/stimulus"
export default class extends Controller {
static targets = [ "source" ]
copy() {
}
}
解释一下这个targets:
当Stimulus加载你的controller类时,它会查看静态数组targets的字符串元素,对于每一个字符串,Stimulus会在controller中添加3个属性。在这里,对于“source”,会添加如下属性:
this.sourceTarget 在controller的域内的第一个source
this.sourceTargets 在controller的域内所有的source组成的一个数组
this.hasSourceTarget 在controller的域内是否有source
我们希望点击按钮时调用controller中的copy()方法,所以我们需要添加data-action=“clipboard#copy“
<button data-action="clipboard#copy">Copy to Clipboard</button>
你可以已经注意到在上面的动作描述符中省略了click->。那是因为Stimulus给button设置了click作为它默认的事件。
某些其他元素也有默认事件。下面是个全部列表:
元素 | 默认事件 |
a | click |
button | click |
details | toggle |
form | submit |
input | input |
input type=“submit” | click |
select | change |
textarea | input |
最终,在copy()方法中,我们获取输入框的内容,调用粘贴板API
copy() {
navigator.clipboard.writeText(this.sourceTarget.value)
}
刷新页面,点击按钮,然后快捷键粘贴到Greet按钮前到输入框,可以看到1234。
到目前为止,在页面上同一时间只有一个controller实例。在页面上同时有一个controller的多个实例也是很正常的。
我们的controller是可以复用的,只要你需要在页面上添加复制内容的按钮,无论是哪个页面,只要把对应的属性值写好,我们的controller都是生效的。
还是上面的例子,再添加另外一个复制按钮:
<div data-controller="clipboard">
PIN: <input data-clipboard-target="source" type="text" value="3737" readonly>
<button data-action="clipboard#copy" class="clipboard-button">Copy to Clipboard</button>
</div>
刷新页面,验证一下两个复制按钮是否都生效。
我们再添加一个可以复制的元素,不用button,我们用a标签,
<div data-controller="clipboard">
PIN: <input data-clipboard-target="source" type="text" value="6666" readonly>
<a href="#" data-action="clipboard#copy" class="clipboard-button">Copy to Clipboard</a>
</div>
Stimulus允许我们使用任何元素,只要它设置了合适的data-action属性,就可以触发复制。
这个例子里,要注意一点,点击链接会使浏览器追踪a标签内的href属性跳转,可以取消这种默认行为,只需要在action中调用 event.preventDefault()就可以了。
copy(event) {
event.preventDefault()
navigator.clipboard.writeText(this.sourceTarget.value)
}
还有另外一个方法,拷贝粘贴板上
copy(event) {
event.preventDefault()
this.sourceTarget.select()
document.execCommand("copy")
}
在本文中,我们看了一个在现实中把浏览器API包装在Stimulus的controller中的例子。还有一个controller的多个实例如何同时出现在页面上,我们还探索了actions和targets如何保持HTML和JavaScript的松散耦合。
下一篇文章,我们将优化一下这个复制粘贴板的功能,让它运行起来更加健壮。
Stimulus:浏览器不支持复制或者弱网条件下,怎么办?
ueuse拥有大量出色的组合。但是量太大,要把它们全部看完可能会让人抓不到重点。下面来介绍一些有用到的组合,它们如下:
检测点击非常简单。但是,当点击发生在一个元素之外时,如何检测?那就有点棘手了。但使用VueUse中的 onClickOutside 组件就很容易能做到这点。代码如下:
<script setup>
import { ref } from 'vue'
import { onClickOutside } from '@vueuse/core'
const container = ref(null)
onClickOutside(container, () => alert('Good. Better to click outside.'))
</script>
<template>
<div>
<p>Hey there, here's some text.</p>
<div class="container" ref="container">
<p>Please don't click in here.</p>
</div>
</div>
</template>
为想要追踪的 container 元素创建一个 ref :
const container = ref(null);
然后我们用元素上的ref属性把它变成一个模板ref。
<div class="container" ref="container">
<p>Please don't click in here.</p>
</div>
有了容器的ref 之后,我们把它和一个处理程序一起传递给onClickOutside组合。
onClickOutside(
container,
() => alert('Good. Better to click outside.')
)
这种可组合对于管理窗口或下拉菜单很有用。当用户点击下拉菜单以外的地方时,你可以关闭它。
模态框也通常表现出这种行为。
事例地址:https://stackblitz.com/edit/vue3-script-setup-with-vite-18scsl?file=src%2FApp.vue
为了拥有可访问的应用程序,正确地管理焦点非常重要。
没有什么比不小心在模态后面加tab,并且无法将焦点返回到模态更糟糕的了。这就是焦点陷阱的作用。
将键盘焦点锁定在一个特定的DOM元素上,不是在整个页面中循环,而是在浏览器本身中循环,键盘焦点只在该DOM元素中循环。
下面是一个使用VueUse的useFocusTrap的例子:
<script setup>
import { ref } from 'vue'
import { useFocusTrap } from '@vueuse/integrations/useFocusTrap'
const container = ref(null)
useFocusTrap(container, { immediate: true })
</script>
<template>
<div>
<button tab-index="-1">Can't click me</button>
<div class="container" ref="container">
<button tab-index="-1">Inside the trap</button>
<button tab-index="-1">Can't break out</button>
<button tab-index="-1">Stuck here forever</button>
</div>
<button tab-index="-1">Can't click me</button>
</div>
</template>
将immediate设置为true,页面加载时,焦点将被放置在 container 元素中。然后,就不可能在该容器之外的地方做标签。
到达第三个按钮后,再次点击tab键将回到第一个按钮。
就像onClickOutside一样,我们首先为 container 设置了模板ref。
const container = ref(null)
<div class="container" ref="container">
<button tab-index="-1">Inside the trap</button>
<button tab-index="-1">Can't break out</button>
<button tab-index="-1">Stuck here forever</button>
</div>
然后我们把这个模板引用传递给useFocusTrap组合。
useFocusTrap(container, { immediate: true });
immediate 选项将自动把焦点设置到容器内第一个可关注的元素上。
事例地址:https://stackblitz.com/edit/vue3-script-setup-with-vite-eocc6w?file=src%2FApp.vue
VueUse为我们提供了一种简单的方法来更新我们应用程序的 head 部分--页面 title、scripts和其他可能放在这里的的东西。
useHead 组合要求我们首先设置一个插件
import { createApp } from 'vue'
import { createHead } from '@vueuse/head'
import App from './App.vue'
const app = createApp(App)
const head = createHead()
app.use(head)
app.mount('#app')
一旦我们使用了这个插件,我们就可以随心所欲地更新标题部分。在这个例子中,我们将在一个按钮上注入一些自定义样式。
<script setup>
import { ref } from 'vue'
import { useHead } from '@vueuse/head'
const styles = ref('')
useHead({
// Inject a style tag into the head
style: [{ children: styles }],
})
const injectStyles = () => {
styles.value = 'button { background: red }'
}
</script>
<template>
<div>
<button @click="injectStyles">Inject new styles</button>
</div>
</template>
首先,我们创建一个ref来表示我们要注入的样式,默认为空:
const styles = ref('');
第二,设置 useHead 将样式注入到页面中。
useHead({
// Inject a style tag into the head
style: [{ children: styles }],
})
然后,添加注入这些样式的方法:
const injectStyles = () => {
styles.value = 'button { background: red }'
}
当然,我们并不局限于注入样式。我们可以在我们的<head>中添加任何这些内容:
事例地址:https://stackblitz.com/edit/vue3-script-setup-with-vite-szhedp?file=src%2FApp.vue
useStorage真的很酷,因为它会自动将 ref 同步到 localstorage,事例如下:
<script setup>
import { useStorage } from '@vueuse/core'
const input = useStorage('unique-key', 'Hello, world!')
</script>
<template>
<div>
<input v-model="input" />
</div>
</template>
第一次加载时, input 显示 'Hello, world!',但最后,它会显示你最后在 input 中输入的内容,因为它被保存在localstorage中。
除了 localstorage,我们也可以指定 sessionstorage:
const input = useStorage('unique-key', 'Hello, world!', sessionStorage)
当然,也可以自己实现存储系统,只要它实现了StorageLike接口。
export interface StorageLike {
getItem(key: string): string | null
setItem(key: string, value: string): void
removeItem(key: string): void
}
v-model指令是很好的语法糖,使双向数据绑定更容易。
但useVModel更进一步,摆脱了一堆没有人真正想写的模板代码。
<script setup>
import { useVModel } from '@vueuse/core'
const props = defineProps({
count: Number,
})
const emit = defineEmits(['update:count'])
const count = useVModel(props, 'count', emit)
</script>
<template>
<div>
<button @click="count = count - 1">-</button>
<button @click="count = 0">Reset to 0</button>
<button @click="count = count + 1">+</button>
</div>
</template>
在这个例子中,我们首先定义了要附加到v-model上的 props:
const props = defineProps({
count: Number,
})
然后我们发出一个事件,使用v-model的命名惯例update:<propName>:
const emit = defineEmits(['update:count'])
现在,我们可以使用useVModel组合来将 prop和事件绑定到一个ref。
const count = useVModel(props, 'count', emit)
每当 prop 发生变化时,这个 count 就会改变。但只要它从这个组件中被改变,它就会发出update:count事件,通过v-model指令触发更新。
我们可以像这样使用这个 Input 组件。
<script setup>
import { ref } from 'vue'
import Input from './components/Input.vue'
const count = ref(50)
</script>
<template>
<div>
<Input v-model:count="count" />
{{ count }}
</div>
</template>
这里的count ref是通过v-model绑定与 Input组件内部的count ref同步的。
事例地址:https://stackblitz.com/edit/vue3-script-setup-with-vite-ut5ap8?file=src%2FApp.vue
随着时间的推移,web应用中的图像变得越来越漂亮。我们已经有了带有srcset的响应式图像,渐进式加载库,以及只有在图像滚动到视口时才会加载的库。
但你知道吗,我们也可以访问图像本身的加载和错误状态?
我以前主要通过监听每个HTML元素发出的onload和onerror事件来做到这一点,但VueUse给我们提供了一个更简单的方法,那就是useImage组合。
<script setup>
import { useImage } from '@vueuse/core'
// Change this to a non-existent URL to see the error state
const url = 'https://source.unsplash.com/random/400x300'
const { isLoading, error } = useImage(
{
src: url,
},
{
// Just to show the loading effect more clearly
delay: 2000,
}
)
</script>
<template>
<div>
<div v-if="isLoading" class="loading gradient"></div>
<div v-else-if="error">Couldn't load the image :(</div>
<img v-else :src="url" />
</div>
</template>
第一步,通过useImage 设置图片的src:
const { isLoading, error } = useImage({ src: url })
获取它返回的isLoading和error引用,以便跟踪状态。这个组合在内部使用useAsyncState,因此它返回的值与该组合的值相同。
安排好后,useImage 就会加载我们的图像并将事件处理程序附加到它上面。
我们所要做的就是在我们的模板中使用相同的URL来使用该图片。由于浏览器会重复使用任何缓存的图片,它将重复使用由useImage加载的图片。
<template>
<div>
<div v-if="isLoading" class="loading gradient"></div>
<div v-else-if="error">Couldn't load the image :(</div>
<img v-else :src="url" />
</div>
</template>
在这里,我们设置了一个基本的加载和错误状态处理程序。当图片正在加载时,我们显示一个带有动画渐变的占位符。如果有错误,我们显示一个错误信息。否则我们可以渲染图像。
UseImage 还有其他一些很棒的特性!如果想让它成为响应式图像,那么它支持srcset和sizes属性,这些属性在幕后传递给img元素。
如果你想把所有内容都放在模板中,还有一个无渲染组件。它的工作原理与组合的相同:
<template>
<UseImage src="https://source.unsplash.com/random/401x301">
<template #loading>
<div class="loading gradient"></div>
</template>
<template #error>
Oops!
</template>
</UseImage>
</template>
事例:https://stackblitz.com/edit/vue3-script-setup-with-vite-d1jsec?file=src%2FApp.vue
最近,每个网站和应用程序似乎都有暗黑模式。最难的部分是造型的改变。但是一旦你有了这些,来回切换就很简单了。
如果你使用的是Tailwind,你只需要在html元素中添加dark类,就可以在整个页面中启用。
<html class="dark"><!-- ... --></html>
然而,在黑暗模式和光明模式之间切换时,有几件事需要考虑。首先,我们要考虑到用户的系统设置。第二,我们要记住他们是否已经推翻了这个选择。
VueUse的useDark组合性为我们把所有这些东西都包起来。默认情况下,它查看系统设置,但任何变化都会被持久化到localStorage,所以设置会被记住。
<script setup>
import { useDark, useToggle } from '@vueuse/core'
const isDark = useDark()
const toggleDark = useToggle(isDark)
</script>
<template>
<div class="container">
Changes with dark/light mode.
<button @click="toggleDark()">
Enable {{ isDark ? 'Light' : 'Dark' }} Mode
</button>
</div>
</template>
黑暗模式的样式:
.dark .container {
background: slategrey;
color: white;
border-color: black;
}
.dark button {
background: lightgrey;
color: black;
}
.dark body {
background: darkgrey;
}
如果你没有使用Tailwind,你可以通过传入一个选项对象来完全定制黑暗模式的应用方式。下面是默认的Tailwind:
const isDark = useDark({
selector: 'html',
attribute: 'class',
valueDark: 'dark',
valueLight: '',
})
也可以提供一个onChanged处理程序,这样你就可以编写任何你需要的Javascript。这两种方法使你可以使它与你已有的任何造型系统一起工作。
Vueuse 拥有一个巨大的库,其中包含出色的组合,而我们在这里只涵盖了其中的一小部分。我强烈建议你花些时间去探索这些文档,看看所有可用的东西。这是一个非常好的资源,它将使你免于大量的模板代码和不断地重新发明车轮。
作者:Noveo 译者:小智 来源:vuemastery 原文:https://www.vuemastery.com/blog/best-vueue-composables
、需求分析
1、需求:点击关闭之后,顶部广告图可以关闭
2、分析:
点击的是关闭按钮
关闭的是父盒子
利用样式的显示和隐藏完成, display:none 隐藏元素 display:block 显示元素
<script src="https://lf6-cdn-tos.bytescm.com/obj/cdn-static-resource/tt_player/tt.player.js?v=20160723"></script>
二、HTML代码准备
准备好一个div盒子,在里面放上图片和一个小的div盒子
HTML代码准备
三、CSS样式设置
1、导入css外部样式文件
导入css外部样式文件
2、给大的div盒子设置宽高1190px*80px
div大盒子样式设置
3、小的div盒子设置宽高20px*20px,背景色为#666,文字X水平居中、行高20px(行高为了垂直居中),鼠标移到上面的时候变为小手(cursor: pointer)
div小盒子样式设置
4、定位小盒子到广告图右上角,利用父相对,子绝对的定位方法,将小盒子移动到距离图片顶部和右侧5px的位置
定位小盒子到广告图右上角
CSS样式设置好后效果图
四、点击关闭功能实现
1、导入js外部文件
导入js外部文件
2、获取元素对象,分别获取大盒子和小盒子的元素对象
获取元素对象
3、点击小盒子时,关闭大盒子(将大盒子隐藏,即将大盒子的display属性值改为none)
点击小盒子时,关闭大盒子
以上就是如何实现京东点击关闭顶部广告功能的方法,你学“废”了吗
我
*请认真填写需求信息,我们会在24小时内与您取得联系。