<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://unpkg.com/vue@2.5.17/dist/vue.js"></script>
<title>Document</title>
</head>
<body>
<div id="app">
hellow
</div>
<script>
new Vue({
el : "#app",
template : "<div>{{msg}}</div>",
data : {
msg : "你好!"
}
})
</script>
</body>
</html>
template 属性中的 字符串标签 会替换 id 为 app 的 标签 ,在template 中可以使用 {{ }} 的方式 调用自己的属性 如msg
示例:
template 优缺点 ,写字符串html 没有编辑器的智能提示 ,编写daim效率低
Vue 全局组件 添加组件的方式 :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://unpkg.com/vue@2.5.17/dist/vue.js"></script>
<title>Document</title>
</head>
<body>
<div id="app">
<my-component></my-component>
</div>
<script>
Vue.component('my-component',{
template : `<div>
<button @click= "clickMe">{{count}}</button>
</div>`,
data : function(){
return {
count : 0
}
},
methods : {
clickMe : function(){
this.count ++;
}
}
})
new Vue({
el : '#app',
})
</script>
</body>
</html>
示例:
需要注意 在 component 函数中 data 是 函数形式的 ,这是为了避免 多个地方都调用该组件时, 数据都是同一个
这种情况是可以模拟的 : 如下 :
var data = {
count : count
}
Vue.component('my-component',{
template : `<div>
<button @click= "clickMe">{{count}}</button>
</div>`,
data : function(){
return data
},
methods : {
clickMe : function(){
this.count ++;
}
}
})
new Vue({
el : '#app',
})
效果:
局部组件的定义 : 这样定义出来的组件只有 #app 可以使用 my-component 组件,
var myConponent = {
template : `<div>
<button @click= "clickMe">{{count}}</button>
</div>`,
data : function(){
return data
},
methods : {
clickMe : function(){
this.count ++;
}
}
}
// Vue.component('my-component',myConponent)
new Vue({
el : '#app',
components : {
'my-component' : myConponent
}
})