1.全局组件、局部组件
<body>
<div id="ppa">
<jspan></jspan>
<!-- <panda></panda> panda是局部组件,在此处无效-->
</div>
<div id="app">
<jspan></jspan>
<panda></panda>
</div>
<script type="text/javascript">
//1.定义全局组件 放到vue的作用域里边
Vue.component('jspan',{
template:'<div style="color:red">我是全局jspan组件</div>',
})
var app = new Vue({
el:'#app',
//2.定义局部组件
components:{
"panda":{
template:'<div style="color:green">我是局部panda组件</div>',
}
}
})
var app = new Vue({
el:'#ppa',
})
</script>
</body>
2.组件属性
<body>
<div id="app">
<panda here="China"></panda>
<!-- 此种写法Vue中必须写fromHere -->
<panda from-here="China"></panda>
<panda v-bind:here="message"></panda>
<panda :here="message"></panda>
</div>
<script type="text/javascript">
var app = new Vue({
el:'#app',
data:{
message:'China',
},
components:{
"panda":{
template:`<div style="color:green">Panda from {{here}}</div>`,
props:['here'],//数组,可以传很多属性
}
}
})
</script>
</body>
3.组件继承
<body>
<div id="app">
<panda></panda>
</div>
<script type="text/javascript">
//在Vue外部声明组件
var cityComponent = {
template:`<div style="color:green;">SiChuan of China.</div>`,
};
var pandaComponent = {
template:`
<div>
<p>Panda from China.</p>
<city></city>
</div>
`,
components:{
"city":cityComponent,//组件继承
}
};
var app = new Vue({
el:'#app',
data:{
//message:'China',
},
components:{
"panda":pandaComponent,
},
})
</script>
</body>
4.组件标签<component></component>
<body>
<div id="app">
<!-- vue定义的标签 可以使用任意自己声明的组件-->
<component v-bind:is="who"></component>
<button @click="changeComponent">ChangeComponent</button>
</div>
<script type="text/javascript">
var componentA = {
template:`<div style="color:red;">I am componentA</div>`
}
var componentB = {
template:`<div style="color:green;">I am componentB</div>`
}
var componentC = {
template:`<div style="color:pink;">I am componentC</div>`
}
var app = new Vue({
el:'#app',
data:{
who:'componentB'
},
components:{
"componentA":componentA,
"componentB":componentB,
"componentC":componentC,
},
methods:{
changeComponent:function(){
if(this.who == "componentA")
{
this.who = "componentB";
}
else if(this.who == "componentB")
{
this.who = "componentC";
}
else{
this.who = "componentA";
}
}
}
})
</script>
</body>