首页 > web前端 > js教程 > 正文

vue组件的3种书写形式详解

小云云
发布: 2017-12-12 14:59:24
原创
1920 人浏览过

本文主要为大家详细介绍了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学习者快速成长!