基本 Vite 香草设置
Basic Vite Vanilla Setup
我想用 Vite vanilla
建立一个非常基本的项目
我用 yarn create @vitejs/app
搭建了这个项目
现在我调整了以下文件:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite App</title>
<link rel="stylesheet" href="style.css">
<script type="module" src="main.js"></script>
</head>
<body>
<div id="app">
<h1>Chat</h1>
Message
<br/>
<textarea placeholder="Message"></textarea>
<button onclick="sendMessage()">Send</button>
</div>
</body>
</html>
style.css
h1 {
color: blue;
}
main.js
console.log('hello main.js')
const chatInput = document.querySelector('textarea')
export function sendMessage() {
let message = chatInput.value
window.alert(message)
chatInput.value = "";
}
我现在在单击“发送”按钮时在浏览器控制台中收到以下错误
client.ts:13 [vite] connecting...
main.js:35 hello main.js
client.ts:43 [vite] connected.
(index):18 Uncaught ReferenceError: sendMessage is not defined
at HTMLButtonElement.onclick ((index):18)
解决方法
我可以通过向按钮添加事件侦听器而不是直接在 HTML
中添加 onclick 来解决该问题
const sendButton = document.querySelector('button')
sendButton.addEventListener('click', sendMessage)
但是为什么不能在 HTML 中对 onclick="sendMessage()"
使用第一种方法?
Main.js
添加为 type=module
。模块创建一个范围以避免名称冲突。
您可以将您的函数公开给 window
对象
import { sendMessage } from './events.js'
window.sendMessage = sendMEssage
或者使用 addEventListener
方法像您一样绑定处理程序。
我想用 Vite vanilla
建立一个非常基本的项目我用 yarn create @vitejs/app
现在我调整了以下文件:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite App</title>
<link rel="stylesheet" href="style.css">
<script type="module" src="main.js"></script>
</head>
<body>
<div id="app">
<h1>Chat</h1>
Message
<br/>
<textarea placeholder="Message"></textarea>
<button onclick="sendMessage()">Send</button>
</div>
</body>
</html>
style.css
h1 {
color: blue;
}
main.js
console.log('hello main.js')
const chatInput = document.querySelector('textarea')
export function sendMessage() {
let message = chatInput.value
window.alert(message)
chatInput.value = "";
}
我现在在单击“发送”按钮时在浏览器控制台中收到以下错误
client.ts:13 [vite] connecting...
main.js:35 hello main.js
client.ts:43 [vite] connected.
(index):18 Uncaught ReferenceError: sendMessage is not defined
at HTMLButtonElement.onclick ((index):18)
解决方法
我可以通过向按钮添加事件侦听器而不是直接在 HTML
中添加 onclick 来解决该问题const sendButton = document.querySelector('button')
sendButton.addEventListener('click', sendMessage)
但是为什么不能在 HTML 中对 onclick="sendMessage()"
使用第一种方法?
Main.js
添加为 type=module
。模块创建一个范围以避免名称冲突。
您可以将您的函数公开给 window
对象
import { sendMessage } from './events.js'
window.sendMessage = sendMEssage
或者使用 addEventListener
方法像您一样绑定处理程序。