vue无webpack直接在浏览器端运行的几种方法

现在开发vue的应用,都是在nodejs下通过vue cli创建项目,然后编写代码,执行webpack devserver调试运行,最后通过webpack打包输出,那么vue可以实现无需webpack就能直接在浏览器上按需加载不同的vue和组件吗?当然可以,而且方案不止一种,下面我们来一个一个介绍一下:
一、Vue3原生支持
vue本来就可以在浏览器中开发,看看这个项目目录,我们先看main.js文件。

main.js
///main.js
import App from './App.js';
import Home from './pages/Home.js';
import Center from './pages/Center.js';
// 2. 定义路由
// 每个路由应该映射一个组件
const routes = [
{
path: '/',
component:Home
},
{
path: '/center',
component:Center
}]
// 3. 创建 router 实例,然后传 `routes` 配置
// 你还可以传别的配置参数, 不过先这么简单着吧。
const router = VueRouter.createRouter({
// 4. 通过 createWebHashHistory() 创建 hash 模式。
history: VueRouter.createWebHashHistory(),
routes, // (缩写) 相当于 routes: routes
})
const app = Vue.createApp({
render: () => Vue.h(App),
});
app.use(router)
app.use(ElementPlus) // 加载ElementPlus
app.mount('#app');
main.js写法跟vue cli的方式有点差异不过组件的写法除了后缀必须为js外其他大致一样,我们看Home.js
import BaseButton from "../component/BaseButton.js"
export default {
name: 'App',
components: {
BaseButton
},
data() {
return {
count: 0,
visible:false
};
},
template: `
<div>
<el-button @click="visible = true">Button</el-button>
Count: {{ count }}
<BaseButton @click="count += 1">
+1
</BaseButton>
<h1>
页面一
</h1>
</div>
`,
};
完整的项目源码地址在bfwstudio上,可直接克隆并直接开发运行,项目webide地址:https://studio.bfw.wiki/Studio/Open.html?projectid=16291885208748360042
二、Vue3-sfc-loader插件支持

; (async () => {
const randvar = Math.random();
const options = {
moduleCache: {
vue: Vue
},
getFile(url) {
return fetch(url+"?rand="+randvar).then(res => {
if (!res.ok) throw Object.assign(new Error(url + ' ' + res.statusText), {
res
});
// ----------------------
return res.text().then(content => {
if (/.*?\.mjs$/.test(url)) {
return {
content: content,
type: ".mjs"
}
}
return content;
});
})
},
addStyle(textC...点击查看剩余70%
网友评论0