首頁  >  文章  >  web前端  >  有哪些vue組件的書寫方法

有哪些vue組件的書寫方法

php中世界最好的语言
php中世界最好的语言原創
2018-04-14 11:49:201778瀏覽

這次帶給大家有哪些vue組件的書寫方法,使用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('my-component',{
      template: '#myComponent'
    })
    new Vue({
      el: '#app'
    })
  </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('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資料夾中

<template>
 <p class="hello">
  <h1>{{ msg }}</h1>
 </p>
</template>
<script>
export default {
 name: 'hello',
 data () {
  return {
   msg: '欢迎!'
  }
 }
}
</script>

app.vue

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

相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:

新手必看的js實作非同步方法

透過JS取得JSON資料並載入的步驟詳解

#

以上是有哪些vue組件的書寫方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn