在 Vue 中,你可以结合 <script type="module"> 和原生 JavaScript 模块系统来进行模块化开发。
1. 创建 JavaScript 模块文件:
创建一个或多个 JavaScript 文件作为模块,例如 utils.js:
// utils.js export function greet(name) { console.log(`Hello, ${name}!`); } export const PI = 3.1415926;
2. 在 Vue 组件中引入模块:
在你的 Vue 组件的 <script> 标签中,使用 type="module" 属性,然后使用 import 语句引入模块。
<template> <div> <button @click="greetUser">点击</button> </div> </template> <script type="module"> import { greet, PI } from './utils.js'; // 调整路径 export default { methods: { greetUser() { greet('World'); console.log('PI:', PI); }, }, }; </script>
3. 配置开发服务器 (vite, webpack):
为了使浏览器能够正确加载模块,你需要配置你的开发服务器。
Vite (推荐): Vite 默认支持原生 ES 模块,你不需要进行额外配置。Webpack: 你需要使用 vue-cli 3.x 或更高版本,并在 vue.config.js 中配置 module 规则:
// vue.config.js module.exports = { configureWebpack: { module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'], }, }, }, ], }, }, };
注意:
浏览器兼容性: <script type="module"> 和原生 JavaScript 模块系统需要较新的浏览器版本支持。你需要根据项目需求考虑浏览器兼容性问题。文件路径: 确保在 import 语句中使用正确的文件路径。通过以上步骤,你就可以在 Vue 中使用 <script type="module"> 进行模块化开发,提高代码可维护性和复用性。
网友回复