vue中組件的定義:
第一種:全局組件
<html>
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="css/animate.min.css" />
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<!--舊版本-->
<!--<script type="text/javascript" src="js/vue.min.js" ></script>-->
</head>
<body>
<div id="box">
<aaa></aaa>
</div>
<script>
var A=Vue.extend({
template:'<h1>標題一</h1>'
});
Vue.component("aaa",A);
new Vue({
el:'#box',
data:{
}
});
</script>
</body>
</html>
var A=Vue.extend({
template:'<h1>標題一</h1>'
});
Vue.component("aaa",A);
等價於:
//另一種編寫方式
Vue.component("bbb",{
template:'<h2>標題二</h2>'
})
需要注意的一點是:組件中放數據的時候,data必須是個函數,而且必須返回一個對象。
var A=Vue.extend({
data:function(){ //數據
return:{
msg:'標題一'
}
},
methods:{ 方法
change:function(){
alert(1);
this.msg='改變後的標題一';
}
},
template:'<h1 @click='change'>{{msg}}</h1>'
});
Vue.component("aaa",A);
第二種:局部組件
var A=Vue.extend({
template:'<h1>標題一</h1>'
});
var vm=new Vue({
el:'#box',
data:{
},
components:{ //局部組件
'aaa':A
}
})
局部組件的另一種編寫方式
var vm=new Vue({
el:'#box',
data:{
},
components:{ //局部組件
'aaa':{
data:function(){
return:{
msg:'標題一'
}
},
template:'<h1>{{msg}}</h1>'
}
}
})
到目前爲止,vue的組件應該是算告一小段了,不過又引發了新的問題,在上述中template都是單一的標籤,如果裏邊有很多標籤,並且嵌套,這樣的話tepmlate中還需要轉義,就是相當麻煩的事情,所以有了下面的組件-模板
<div id="box">
<aaa></aaa>
<template id='temp'>
<h1>{{msg}}</h1>
</template>
</div>
<script>
var A=Vue.extend({
data:function(){
return{
msg:'標題',
}
},
template:"#temp"
})
new Vue({
el:'#box',
data:{
msg:''
},
components:{
'aaa':A
}
});
</script>
有的時候,在不同組件之間進行動態切換是非常有用的,這時候就需要用到動態組件:
<component v-bind:is="組件名稱"></component>
完整代碼:
<div id="box">
<input type="button" value="按鈕1" @click="afun">
<input type="button" value="按鈕2" @click="bfun">
<component :is='isab'></component>
</div>
<script>
var a=Vue.component("aaa",{
template:'<p>aaaaa</p>'
})
var b=Vue.component("bbb",{
template:'<p>bbbbb</p>'
})
window.onload=function(){
new Vue({
el:'#box',
data:{
isab:"aaa"
},
methods:{
afun:function(){
this.isab="aaa"
},
bfun:function(){
this.isab="bbb"
}
}
,
components:{
"aaa":a,
"bbb":b
}
})
}
</script>