之前只是用过第三种方式去创建组件,最近接触到第一种写法的项目,所以写下了下面的内容
- 使用
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>
- 单文件组件
以.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>