【发布时间】:2021-02-02 01:20:22
【问题描述】:
我正在使用 alpine.js 创建一个应用程序
这是我的index.html 文件的上下文
<!DOCTYPE html>
<html>
<head>
<title>Hello Alpine</title>
<meta charset="UTF-8" />
</head>
<body>
<div id="app" x-data="app()">
<div>
<button x-on:click="open">Open</button>
<div x-show="isOpen()" x-on:click.away="close">
// Dropdown
</div>
</div>
</div>
<script src="src/index.js"></script>
<script>
function app() {
return {
show: false,
open() {
this.show = true;
},
close() {
this.show = false;
},
isOpen() {
return this.show === true;
}
};
}
</script>
</body>
</html>
此代码运行良好,但是,如果我将 app 函数移动到 index.js,我会在控制台中收到错误消息。
index.html:
<!DOCTYPE html>
<html>
<head>
<title>Hello Alpine</title>
<meta charset="UTF-8" />
</head>
<body>
<div id="app" x-data="app()">
<div>
<button x-on:click="open">Open</button>
<div x-show="isOpen()" x-on:click.away="close">
// Dropdown
</div>
</div>
</div>
<script src="src/index.js"></script>
</body>
</html>
和 index.js
import "./styles.css";
import "alpinejs";
function app() {
return {
show: false,
open() {
this.show = true;
},
close() {
this.show = false;
},
isOpen() {
return this.show === true;
}
};
}
当我运行此代码时,我收到以下错误:
alpine.js:1907 Uncaught TypeError: app is not a function 在 eval 处(在 tryCatch.el.el (alpine.js:NaN) 处进行评估,:3:54)
CodeSandbox 链接是here
【问题讨论】:
标签: javascript html parcel alpine.js