開始之前,需要添加 Bootstrap 到 Vue CLI 項目,由於目前所有前端資源都已經通過 NPM 進行管理,所以需要安裝對應的依賴包:
npm install bootstrap jquery popper.js
然後在 src/main.js 中引入 Bootstrap 的腳本和樣式文件:
import Vue from 'vue'
import App from './App.vue'
import 'bootstrap'
import 'bootstrap/dist/css/bootstrap.min.css'
...
接下來,就可以正式編寫單文件組件了。
編寫 ModalExample 組件我們將 vue_learning/component/slot.html 中的 modal-example 組件拆分出來,在 vue_learning/demo-project/src/components 目錄下新建一個單文件組件 ModalExample.vue,將 modal-example 組件代碼按照 Vue Loader 指定的格式填充到對應位置:
<template>
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">
<slot name="header"></slot>
</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<ul>
<li v-for="language in languages" v-bind:key="language.id">
<slot v-bind:language="language">{{ language.name }}</slot>
</li>
</ul>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'ModalExample',
props: ['languages']
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
ul li {
text-align: left;
}
</style>
除了父級作用域傳入的 languages 數據結構有所調整外,其他都保持一致,相信有了前面的鋪墊,看懂上面的組件代碼對你而言已經不是什麼難事。
註冊 ModalExample 組件接下來,我們在 App.vue 中引入 ModalExample 組件:
<template>
<div id="app">
<img alt="Vue logo" src="./assets/logo.png">
<hr>
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
模態框
</button>
<!-- Modal -->
<ModalExample :languages="this.languages">
<template slot="header">{{ this.title }}</template>
<template scope="bodyProps">
{{ bodyProps.language.name }}
<span v-if="bodyProps.language.name === 'PHP'">☑️</span>
</template>
</ModalExample>
</div>
</template>
<script>
import ModalExample from './components/ModalExample.vue'
export default {
name: 'App',
data() {
return {
'title': 'Web 程式語言',
'languages': [
{'id': 1, 'name': 'PHP'},
{'id': 2, 'name': 'JavaScript'},
{'id': 3, 'name': 'Golang'}
]
}
},
components: {
ModalExample
}
}
</script>
...
我們將之前的 HelloWorld 組件調整為 ModalExample 組件,可以看到,這裡只是按照 Vue Loader 單文件組件規範重新編排了代碼,主體邏輯和之前混合在 HTML 文檔中的組件註冊並沒有什麼差別。
驗證單文件組件渲染需要指出的是,Vue CLI 項目在通過 npm run serve 命令啟動服務時,會附帶開箱即用的模塊熱重載(Hot Module Replacement),所以 src/main.js 及其依賴的任意 JavaScript 代碼(包括單文件 Vue 組件)調整並保存後,會自動進行重新編譯打包。
因此,在瀏覽器刷新 http://localhost:8080 頁面,就可以看到如下頁面渲染結果:
點擊「模態框」按鈕,可以看到彈出的模態框如下,和之前渲染的效果完全一致:
這同時也驗證了 Bootstrap 框架已經成功引入。
當然,這只是一個功能非常簡單的單文件 Vue 組件,接下來,學院君會陸續基於 Vue 組件實現一些更加複雜的功能,比如交互表單、單頁面應用等。
本系列教程首發在Laravel學院(laravelacademy.org),你可以點擊頁面左下角閱讀原文連結查看最新更新的教程。