Vue組件模板的幾種書寫形式(3種)
1.第一種使用script標(biāo)簽
<!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>標(biāo)簽時,type指定為text/x-template,意在告訴瀏覽器這不是一段js腳本,
瀏覽器在解析HTML文檔時會忽略<script>標(biāo)簽內(nèi)定義的內(nèi)容。
2.第二種使用template標(biāo)簽
<!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>
當(dāng)然,如果template內(nèi)容少的話,我們可以直接在組件中書寫,而不需要用template標(biāo)簽。像下面這樣:
Vue.component('test-component',{ template:`<h1>this is test,{{test}}</h1>`, data(){ return{ test:"hello test" } } })
3.第三種 單文件組件
這種方法常用在vue單頁應(yīng)用中
創(chuàng)建.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種)的詳細(xì)內(nèi)容,更多關(guān)于Vue 組件模板請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
vscode中vue代碼提示與補(bǔ)全沒反應(yīng)解決(vetur問題)
這篇文章主要給大家介紹了關(guān)于vscode中vue代碼提示與補(bǔ)全沒反應(yīng)解決(vetur問題)的相關(guān)資料,文中通過圖文將解決的方法介紹的非常詳細(xì),需要的朋友可以參考下2023-03-03vue中的雙向數(shù)據(jù)綁定原理與常見操作技巧詳解
這篇文章主要介紹了vue中的雙向數(shù)據(jù)綁定原理與常見操作技巧,結(jié)合實(shí)例形式詳細(xì)分析了vue中雙向數(shù)據(jù)綁定的概念、原理、常見操作技巧與相關(guān)注意事項(xiàng),需要的朋友可以參考下2020-03-03vue使用vue-i18n實(shí)現(xiàn)國際化的實(shí)現(xiàn)代碼
本篇文章主要介紹了vue使用vue-i18n實(shí)現(xiàn)國際化的實(shí)現(xiàn)代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-04-04淺談vue中document.getElementById()拿到的是原值的問題
這篇文章主要介紹了淺談vue中document.getElementById()拿到的是原值的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07Vue3 directive自定義指令內(nèi)部實(shí)現(xiàn)示例
這篇文章主要為大家介紹了Vue3 directive自定義指令內(nèi)部實(shí)現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-12-12Vue3中v-if和v-for優(yōu)先級實(shí)例詳解
Vue.js中使用最多的兩個指令就是v-if和v-for,下面這篇文章主要給大家介紹了關(guān)于Vue3中v-if和v-for優(yōu)先級的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-09-09