如题所示:代码如下。
一、.js文件内容如下
// getmousexy.js(修正版)
import { ref, onMounted, onUnmounted } from 'vue'; // 注意这里从 'vue' 导入
export function useMouse() {
const x = ref(0);
const y = ref(0);
const update = (e) => {
x.value = e.pageX;
y.value = e.pageY;
};
onMounted(() => {
window.addEventListener('mousemove', update);
});
onUnmounted(() => {
window.removeEventListener('mousemove', update);
});
return { x, y };
}
二、VUE3中的HTML5代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>html5通过vue3调用*.js文件</title>
<!-- 1. 引入 Vue 3 -->
<script type="importmap">
{
"imports": {
"vue": "./js/v3.2.8/vue.esm-browser.js"
}
}
</script>
</head>
<body>
<div id="app">
<h1>鼠标位置跟踪</h1>
<p>X 坐标: {{ x }}</p>
<p>Y 坐标: {{ y }}</p>
</div>
<!-- 2. 引入自定义 hook 文件(注意使用 type="module") -->
<script type="module">
// 导入 Vue 相关 API
import { createApp } from 'vue';
// 导入自定义 hook(确保 getmouse.js 在相同目录)
import { useMouse } from './getmousexy.js';
// 创建 Vue 应用
const app = createApp({
setup() {
// 调用自定义 hook
const { x, y } = useMouse();
// 返回模板需要使用的数据
return { x, y }
}
});
app.mount('#app');
</script>
</body>
</html>
请注意如上红色的内容,就是这里了,相当关键。