跳到主要内容

扩展 Alpine

Alpine 提供了多种扩展方式。事实上,Alpine 中每个可用的指令和魔法都使用了这些 API。

生命周期注意事项

这些 API 必须在 Alpine 下载并可用之后、初始化页面本身之前注册。

通过 script 标签

<script src="/js/alpine.js" defer></script>
<div x-data x-foo></div>
<script>
document.addEventListener('alpine:init', () => {
Alpine.directive('foo', ...)
})
</script>

通过 NPM

import Alpine from 'alpinejs'
Alpine.directive('foo', ...)
window.Alpine = Alpine
window.Alpine.start()

自定义指令

方法签名

Alpine.directive('[name]', (el, { value, modifiers, expression }, { Alpine, effect, cleanup }) => {})
  
name指令名称,"foo"对应 x-foo
el指令所添加的 DOM 元素
value冒号后的部分,如 x-foo:bar 中的 'bar'
modifiers点号分隔的附加项数组
expression指令的属性值部分
AlpineAlpine 全局对象
effect创建响应式效果,指令从 DOM 移除时自动清理
cleanup注册指令移除时的回调

简单示例

Alpine.directive('uppercase', el => {
el.textContent = el.textContent.toUpperCase()
})
<span x-uppercase>Hello World!</span>

求值表达式

Alpine.directive('log', (el, { expression }, { evaluate }) => {
console.log(evaluate(expression))
})

响应式效果

Alpine.directive('log', (el, { expression }, { evaluateLater, effect }) => {
let getThingToLog = evaluateLater(expression)
effect(() => {
getThingToLog(thingToLog => { console.log(thingToLog) })
})
})

清理

Alpine.directive('...', (el, {}, { cleanup }) => {
let handler = () => {}
window.addEventListener('click', handler)
cleanup(() => { window.removeEventListener('click', handler) })
})

自定义顺序

Alpine.directive('foo', (el, ...) => { ... }).before('bind')

自定义魔法属性

Alpine.magic('[name]', (el, { Alpine }) => {})

魔法属性

Alpine.magic('now', () => (new Date).toLocaleTimeString())
<span x-text="$now"></span>

魔法函数

Alpine.magic('clipboard', () => subject => navigator.clipboard.writeText(subject))
<button @click="$clipboard('hello world')">Copy</button>

编写和共享插件

Script 引入

<script src="/js/foo.js" defer></script>
<script src="/js/alpine.js" defer></script>
// /js/foo.js
document.addEventListener('alpine:init', () => {
window.Alpine.directive('foo', ...)
window.Alpine.magic('foo', ...)
})

打包模块

import Alpine from 'alpinejs'
import foo from 'foo'
Alpine.plugin(foo)
window.Alpine = Alpine
window.Alpine.start()
// foo 源码
export default function (Alpine) {
Alpine.directive('foo', ...)
Alpine.magic('foo', ...)
}