Vue組件模板的幾種書寫形式(3種)

1.第一種使用script標(biāo)簽

從事資陽服務(wù)器托管,服務(wù)器租用,云主機(jī),網(wǎng)絡(luò)空間,域名注冊(cè),CDN,網(wǎng)絡(luò)代維等服務(wù)。

<!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>
    //全局注冊(cè)組件
    Vue.component('test-component',{
      template: '#testComponent', 
      data(){
       return{
        test:"hello"
       }
      }
    })

    new Vue({
      el: '#app'
    })
  </script>
</html>

注意:使用<script>標(biāo)簽時(shí),type指定為text/x-template,意在告訴瀏覽器這不是一段js腳本,
瀏覽器在解析HTML文檔時(shí)會(huì)忽略<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:`<h2>this is test,{{test}}</h2>`,
    data(){
     return{
       test:"hello test"
       }
      }
  })

3.第三種 單文件組件

這種方法常用在vue單頁應(yīng)用中

創(chuàng)建.vue后綴的文件,組件Hello.vue,放到components文件夾中

<template>
 <div class="hello">
  <h2>{{ msg }}</h2>
 </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 組件模板請(qǐng)關(guān)注創(chuàng)新互聯(lián)其它相關(guān)文章!

網(wǎng)站名稱:Vue組件模板的幾種書寫形式(3種)
URL標(biāo)題:http://bm7419.com/article8/gejeop.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供定制開發(fā)、域名注冊(cè)、靜態(tài)網(wǎng)站面包屑導(dǎo)航、網(wǎng)站收錄品牌網(wǎng)站制作

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)站建設(shè)公司