首頁 > web前端 > js教程 > 主體

vue組件的3種書寫形式詳解

小云云
發布: 2017-12-12 14:59:24
原創
1919 人瀏覽過

本文主要為大家詳細介紹了3種vue組件的書寫形式,具有一定的參考價值,有興趣的小夥伴們可以參考一下,希望能幫助大家。

第一種使用script標籤


<!DOCTYPE html>
<html>
  <body>
    <p id="app">
      <my-component></my-component>
    </p>

    <-- 注意:使用<script>标签时,type指定为text/x-template,意在告诉浏览器这不是一段js脚本,浏览器在解析HTML文档时会忽略<script>标签内定义的内容。-->

    <script type="text/x-template" id="myComponent">//注意 type 和id。
      <p>This is a component!</p>
    </script>
  </body>
  <script src="js/vue.js"></script>
  <script>
    //全局注册组件
    Vue.component(&#39;my-component&#39;,{
      template: &#39;#myComponent&#39;
    })

    new Vue({
      el: &#39;#app&#39;
    })

  </script>
</html>
登入後複製


第二種使用template標籤


<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title></title>
  </head>
  <body>
    <p id="app">
      <my-component></my-component>
    </p>

    <template id="myComponent">
      <p>This is a component!</p>
    </template>
  </body>
  <script src="js/vue.js"></script>
  <script>

    Vue.component(&#39;my-component&#39;,{
      template: &#39;#myComponent&#39;
    })

    new Vue({
      el: &#39;#app&#39;
    })

  </script>
</html>
登入後複製


#第三種單一檔案元件

這種方法常用在vue單頁應用程式中。詳情請見官網:https://cn.vuejs.org/v2/guide/single-file-components.html

建立.vue後綴的檔案,組件Hello.vue,放到components文件夾中


<template>
 <p class="hello">
  <h1>{{ msg }}</h1>
 </p>
</template>

<script>
export default {
 name: &#39;hello&#39;,
 data () {
  return {
   msg: &#39;欢迎!&#39;
  }
 }
}
</script>
登入後複製


#app.vue


<!-- 展示模板 -->
<template>
 <p id="app">
  <img src="./assets/logo.png">
  <hello></hello>
 </p>
</template>

<script>
// 导入组件
import Hello from &#39;./components/Hello&#39;

export default {
 name: &#39;app&#39;,
 components: {
  Hello
 }
}
</script>
<!-- 样式代码 -->
<style>
#app {
 font-family: &#39;Avenir&#39;, Helvetica, Arial, sans-serif;
 -webkit-font-smoothing: antialiased;
 -moz-osx-font-smoothing: grayscale;
 text-align: center;
 color: #2c3e50;
 margin-top: 60px;
}
</style>
登入後複製


相關推薦:

Vue元件選項props

#vue元件如何發佈到npm

vue2.0資料雙向綁定與表單bootstrap+vue元件

#

以上是vue組件的3種書寫形式詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!