【问题标题】:Access Alpine to create magic properties from standalone js file访问 Alpine 以从独立的 js 文件创建魔术属性
【发布时间】: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


    【解决方案1】:

    当您使用defer attribute 时,浏览器会在文档解析后执行脚本。您还必须将 defer 属性添加到 custom.js 脚本中,或者将魔术定义嵌入到 alpine:init 事件侦听器块中:

    document.addEventListener('alpine:init', () => {
        Alpine.magic('post', function () {
            return function (url, data = {}) {
                return fetch(url, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    redirect: 'follow',
                    body: JSON.stringify(data)
                });
            }
        });
    })
    

    这确保了魔术定义仅在 Alpine.js 核心准备好之后发生。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-19
      • 2019-05-24
      • 2020-12-25
      • 1970-01-01
      • 2011-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多