Dzwebs.Net

撰写电脑技术杂文十余年

VUE3在HTML5中调用.js文件

Admin | 2025-4-7 19:25:24 | 被阅次数 | 50

温馨提示!

如果未能解决您的问题,请点击搜索;登陆可复制文章,点击登陆

    如题所示:代码如下。

    一、.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>

    请注意如上红色的内容,就是这里了,相当关键。


该杂文来自: 最新技术

上一篇:rust之RefCell配合Option和struct可修改缓存

下一篇:vue3同一个HTML5页面,通过type="module"创建多个

网站备案号:

网站备案号:滇ICP备11001339号-7

版权属性:

Copyright 2007-2021-forever Inc. all Rights Reserved.

联系方式:

Email:dzwebs@126.com QQ:83539231 访问统计