Vue组件的书写形式

之前只是用过第三种方式去创建组件,最近接触到第一种写法的项目,所以写下了下面的内容

  1. 使用script标签
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
</head>
<body>
    <div id='index-container'>
    </div>

    <script type="text/x-template" id="index-template"> //注意 type 和id
        <div class="container index-container" id="container">
          <!-- 这里面写上相应的html代码,才能保证添加的事件正常响应 -->
        </div>
    </script>
</body>
</html>
/* index.js */
require(['./asset/js/vue.min'], function (Vue) {
    var tmpIndex = new Vue({
        el: '#index-container',
        template: '#index-template',
        data: { ... },
        ...
    });
});

type指定为text/x-template,意在告诉浏览器这不是一段js脚本,浏览器在解析HTML文档时会忽略\

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title></title>
</head>
<body>
    <div id='container'>
        <index-tmp></index-tmp>
    </div>

    <template id="indexTmp">
        <div>...</div>
    </template>

    <script type="vue.js"></script>
    <script>
        Vue.component('index-tmp',{
            template: '#indexTmp'
        });

        new Vue({
            el: '#container'
        });

    </script>
</body>
</html>
  1. 单文件组件

以.vue为后缀的文件

<!-- Index.vue -->
<template>
  <div class="index">
    <h1>{{ msg }}</h1>
  </div>
</template>

<script>
export default {
  name: 'index',
  data () {
    return {
      msg: 'Vue Template'
    }
  }
}
</script>
<template>
  <div id="app">
    <img src="./assets/logo.png">
    <index></index>
  </div>
</template>

<script>
// 导入组件
import Index from './components/Index'

export default {
  name: 'app',
  components: {
    Index
  }
}
</script>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值