请教关于 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,应该如何解决?
- 是不是第三种方式有什么弊端所以不被推荐?因为我总感觉它更方便组织管理代码。(也许是我的错觉)
- 有什么更好的方式,或是最佳实践?
望各位不吝赐教,多谢!
推荐文章: