<!DOCTYPE html> <html> <body> <div id="app"> <my-component></my-component> </div> <-- 注意:使用<script>標籤時,type指定爲text/x-template,意在告訴瀏覽器這不是一段js腳本,瀏覽器在解析HTML文檔時會忽略<script>標籤內定義的內容。--> <script type="text/x-template" id="myComponent">//注意 type 和id。 <div>This is a component!</div> </script> </body> <script src="js/vue.js"></script> <script> //全局註冊組件 Vue.component('my-component',{ template: '#myComponent' }) new Vue({ el: '#app' }) </script> </html>
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> </head> <body> <div id="app"> <my-component></my-component> </div> <template id="myComponent"> <div>This is a component!</div> </template> </body> <script src="js/vue.js"></script> <script> Vue.component('my-component',{ template: '#myComponent' }) new Vue({ el: '#app' }) </script> </html>
這種方法經常使用在vue單頁應用中。詳情看官網:https://cn.vuejs.org/v2/guide/single-file-components.html
建立.vue後綴的文件,組件Hello.vue,放到components文件夾中html
<template> <div class="hello"> <h1>{{ msg }}</h1> </div> </template> <script> export default { name: 'hello', data () { return { msg: '歡迎!' } } } </script>
app.vuevue
<!-- 展現模板 --> <template> <div id="app"> <img src="./assets/logo.png"> <hello></hello> </div> </template> <script> // 導入組件 import Hello from './components/Hello' export default { name: 'app', components: { Hello } } </script> <!-- 樣式代碼 --> <style> #app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>