1.第一種使用script標簽
<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title></title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div id="app"> <test-component></test-component> </div> <script type="text/x-template" id="testComponent"><!-- 注意 type 和id。 --> <div>{{test}} look test component!</div> </script> </body> <script> //全局注冊組件 Vue.component('test-component',{ template: '#testComponent', data(){ return{ test:"hello" } } }) new Vue({ el: '#app' }) </script></html>注意:使用<script>標簽時,type指定為text/x-template,意在告訴瀏覽器這不是一段js腳本,
瀏覽器在解析HTML文檔時會忽略<script>標簽內定義的內容。
2.第二種使用template標簽
<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <title></title> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script> </head> <body> <div id="app"> <test-component></test-component> </div> <template id="testComponent"> <div>look test component!</div> </template> </body> <script> Vue.component('test-component',{ template: '#testComponent' }) new Vue({ el: '#app' }) </script></html>當然,如果template內容少的話,我們可以直接在組件中書寫,而不需要用template標簽。像下面這樣:
Vue.component('test-component',{ template:`<h1>this is test,{{test}}</h1>`, data(){ return{ test:"hello test" } } })3.第三種 單文件組件
這種方法常用在vue單頁應用中
創建.vue后綴的文件,組件Hello.vue,放到components文件夾中
<template> <div class="hello"> <h1>{{ msg }}</h1> </div></template><script>export default { name: 'hello', data () { return { msg: '歡迎!' } }}</script>app.vue<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>以上就是Vue組件模板的幾種書寫形式(3種)的詳細內容,更多關于Vue 組件模板請關注錯新站長站其它相關文章!
新聞熱點
疑難解答
圖片精選