【发布时间】:2022-01-20 17:26:10
【问题描述】:
我尝试在现有页面中实现 Alpine JS。
为此,我使用的是 CDN 版本的 Alpine,我在 <head> 中加载它:
<script defer src="https://unpkg.com/alpinejs@3.x.x/dist/cdn.min.js"></script>
现在我正在尝试从 custom.js 文件中访问 Alpine,该文件在我的页面页脚中自动加载:
Alpine.magic('post', function () {
return function (url, data = {}) {
return fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
redirect: 'follow',
body: JSON.stringify(data)
});
}
});
在我的内容中我尝试了这个:
<div x-data>
<h1>Alpine Test</h1>
<button type="button" @click="$post('/api/users', { name: 'John Doe' })">Add user</button>
</div>
点击按钮,出现此错误:
Uncaught ReferenceError: $post is not defined
我也用window.Alpine尝试过,没有成功。
如何在不使用模块的情况下添加魔法属性和类似的东西?
【问题讨论】:
标签: javascript alpine.js alpinejs