请教关于 Laravel Blade 中 Vue 的几种使用方式
这里不讨论单页应用,因为我觉得对SEO不利(个人愚见)。
第一种:使用一个Vue Component,这是官方文档中的示例用法,运行成功。但是我觉得用一整个Component不太灵活,因为有些部件有按需变换。
resources/views/home.blade.php
<!doctype html>
<html lang="zh-CN">
<head>
...
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
...
</head>
<body>
<!-- 运行成功 -->
<div id="app">
<example-component></example-component>
</div>
<script src="{{ asset('js/app.js') }}" defer></script>
</body>
</html>
第二种:使用多个Vue Components,曾Google到一个日本网友是这么用的,也就是将一个Component拆分为多个。
resources/views/home.blade.php
<!doctype html>
<html lang="zh-CN">
<head>
...
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
...
</head>
<body>
<!-- 也可以运行成功 -->
<div id="a">
<a-component></a-component>
</div>
<div id="b">
<b-component></b-component>
</div>
<div id="c">
<c-component></c-component>
</div>
<script src="{{ asset('js/app.js') }}" defer></script>
</body>
</html>
第三种:于是我就想,这样不是很麻烦么?又要组织管理Blade,又要组织管理Component,两头转悠,难道就不能用传统方式,直接把Vue代码写在Blade代码里管理?然而,它果然就报错了:Uncaught ReferenceError: Vue is not defined
resources/views/home.blade.php
<!doctype html>
<html lang="zh-CN">
<head>
...
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
...
</head>
<body>
<!-- 报错:Uncaught ReferenceError: Vue is not defined -->
<div id="app">
<v-btn>Hello World</v-btn>
</div>
<script src="{{ asset('js/app.js') }}" defer></script>
<script>
new Vue({
el: '#app',
});
</script>
</body>
</html>
不应该啊,app.js里已经引用了Vue啊,为什么会not defined呢?
resources/js/app.js
...
window.Vue = require('vue');
...
因为刚开始用,还闹不明白,百度和Google了好几天,Stackoverflow也去提问了,依旧不知所以然,因此特来求教:
- 为什么第三种方式会出现Vue is not defined,应该如何解决?
- 是不是第三种方式有什么弊端所以不被推荐?因为我总感觉它更方便组织管理代码。(也许是我的错觉)
- 有什么更好的方式,或是最佳实践?
望各位不吝赐教,多谢!
关于 LearnKu
我也不太懂,不过这是我的想法。
我觉得是 Blade 支持,所以你才可以在 Blade 代码里面那么写, 经过 Laravel 注册的,所以能用,毕竟编译 Blade 是 Laravel,不是 Vue。Laravel 充当中间媒介编译,这样才不会冲突,效率也好,当然像你说的那样麻烦些。不过很少这么用,都是在 JavaScript 文件里写 Vue。
Laravel 编译 Blade 时,顺便用 Babel(注意不是 Blade) 编译了你的 Vue 组件。
前后分离,也就是纯 Vue 的时候,当然也是编译你的 *.vue 代码。
我一开始是用 Laravel,后面
回帖前,还在写 Next.js 呢