Vue2.0 【第二季】第9节 Component 标签
目录
第9节 Component 标签
component标签是Vue框架自定义的标签,它的用途就是可以动态绑定我们的组件,根据数据的不同更换不同的组件。
1、我们先在构造器外部定义三个不同的组件,分别是componentA,componentB和componentC
var componentA={
template:`<div style="color:red">I'm componentA.</div>`
}
var componentB={
template:`div style="color:green">I'm componentB.</div>`
}
var componentC={
template:`<div style="color:pink">I'm componentC.</div>`
}
2、我们在构造器的components选项里加入这三个组件
var app = new Vue({
el:'#app',
data:{
who:'componentA'
},
components:{
"componentA":componentA,
"componentB":componentB,
"componentC":componentC,
}
})
3、我们在html里插入component标签,并绑定who数据,根据who的值不同,调用不同的组件
<div id="app">
<component v-bind:is="who"></component>
</div>
这就是我们的组件标签的基本用法。我们提高一下,给页面加个按钮,每点一下更换一个组件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>component-4</title>
<script type="text/javascript" src="../assets/js/vue.js"></script>
</head>
<body>
<h1>component-4</h1>
<hr>
<div id="app">
<component v-bind:is="who"></component>
<button @click="changeComponent">changeComponent</button>
</div>
<script type="text/javascript">
var componentA={
template:`<div style="color:red">I'm componentA.</div>`
}
var componentB={
template:`div style="color:green">I'm componentB.</div>`
}
var componentC={
template:`<div style="color:pink">I'm componentC.</div>`
}
var app = new Vue({
el:'#app',
data:{
who:'componentA'
},
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>
</html>
浏览器效果: