<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.box {
background-color: pink;
height: 100px;
width: 100px;
}
</style>
</head>
<body>
<div id="app">
<h1>{{ message }}</h1>
<!-- ① ② ③-->
<my-template></my-template>
</div>
</body>
<!-- 类型必须指定为text/x-template -->
<script type="text/x-template" id="my-template">
<!-- 只能包含一个根元素,这个元素不能有兄弟 -->
<div>
<button v-on:click="change">点击</button>
<input type="checkbox" v-model="seen">
<div v-if="seen" class="box"></div>
</div>
</script>
<script src="node_modules/vue/dist/vue.js"></script>
<script>
// 第一种方式,只适用于简短的字符串,只能包含一个根元素,这个元素不能有兄弟
// Vue.component('my-template', {
// template: '<div>哈哈,开心!</div>'
// })
// 第二种方式,和模板引擎template相似
// Vue.component('my-template', {
//注意选择器带#了。。。。。。。
// template: '#my-template'
// })
// 第三种方式
Vue.component('my-template', {
//data必须是个方法,返回的对象是要渲染的数据
data: function () {
return {
message: 'hellow vue.js',
seen: true
}
},
template: '#my-template',
methods: {
change: function () {
// this.message访问的是这个component里面的data数据里的message
window.alert(this.message)
}
}
})
//第三种方法里面渲染的数据和这个无关,因为组件有自己的作用域
var app = new Vue({
el: '#app',
data: {
message: 'hellow vue.js'
}
})
</script>
</html>