所謂組件化思想,顧名思義就是化繁爲簡,把一個整體拆成多個模塊,一個模塊爲一個組件來實現。
全局組件:使用Vue.component("組件名",{
props:['屬性名'],
template:'html模板'
});如下圖
源碼如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>全局組件</title>
<script src="vue.js"></script>
</head>
<body>
<div id = 'app2'>
<input type='text' v-model='inputVal'/>
<button @click='addToList'>提交</button>
<ul >
<todo-item v-bind:con1="item" v-for="item in list"></todo-item>
</ul>
</div>
<script>
Vue.component("TodoItem",{
props:['con1'],
template:'<li>{{con1}}</li>'
});
var app = new Vue({
el:'#app2',
data:{
list:[],
inputVal : ''
},
methods:{
addToList:function(){
this.$data.list.push(this.inputVal);
this.inputVal = '';
}
}
});
</script>
</body>
</html>
局部組件,如下圖,對比上面全局組件看看啥差別,個人喜歡用全局組件
源碼如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>局部組件</title>
<script src="vue.js"></script>
</head>
<body>
<div id = 'app2'>
<input type='text' v-model='inputVal'/>
<button @click='addToList'>提交</button>
<ul >
<com v-bind:con1="item" v-for="item in list"></com>
</ul>
</div>
<script>
var com = {
props:['con1'],
template:'<li>{{con1}}</li>'
};
var app = new Vue({
el:'#app2',
data:{
list:[],
inputVal : ''
},
components:{
com:com
},
methods:{
addToList:function(){
this.$data.list.push(this.inputVal);
this.inputVal = '';
}
}
});
</script>
</body>
</html>