vue組件實(shí)現(xiàn)Tab切換功能
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Demo</title>
<script src="https://cdn.bootcss.com/vue/2.4.1/vue.min.js"></script>
</head>
<body>
<div id="app">
<div :is="tabShow"></div>
<button @click="tab('A')">tab1</button>
<button @click="tab('B')">tab2</button>
<button @click="tab('C')">tab3</button>
<button @click="tab('D')">tab4</button>
</div>
<script>
A = {
template:`<h1>我是第一一一個(gè)tab</h1>`
}
B = {
template:`<h1>我是第二二二個(gè)tab</h1>`
}
C = {
template:`<h1>我是第三三三個(gè)tab</h1>`
}
D = {
template:`<h1>我是第四四四個(gè)tab</h1>`
}
new Vue({
el:'#app',
data(){
return {
tabShow:'A'
}
},
components:{
'A': A,
'B': B,
'C': C,
'D': D
},
methods:{
tab(currentShowTab){
this.tabShow = currentShowTab;
}
}
})
</script>
</body>
</html>
兩個(gè)組件方式,還有一種是 .vue 為后綴的文件組件,需要模塊化才能用
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Demo</title>
<script src="https://unpkg.com/vue"></script>
</head>
<body>
<div id="app">
<!-- 一個(gè)全局化組件 hello -->
<hello></hello>
<hr>
<!-- 一個(gè)局部組件 world -->
<world></world>
</div>
<script>
//注意:組件要寫在實(shí)例之前棺滞,不然就會(huì)報(bào)錯(cuò)
Vue.component('hello',{
template:`<h1>我是一個(gè)全局話組件</h1>`
});
//局部組價(jià) 需要用components 去注冊(cè)
world = {
template:`<h2>我是一個(gè)局部組件</h2>`
}
//實(shí)例
new Vue({
el:'#app',
data(){
return {}
},
//components 注冊(cè)world組件
components:{
'world': world
}
})
</script>
</body>
</html>
單項(xiàng)數(shù)據(jù)流纷铣,父組件向子組件傳參數(shù),用props接受
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Demo</title>
<script src="https://unpkg.com/vue"></script>
</head>
<body>
<div id="app">
<!-- 一個(gè)局部組件world贡避, 把message數(shù)據(jù)傳給子組件-->
<world :here="message"></world>
</div>
<script>
world = {
// props接收父組件傳過(guò)來(lái)的here
props:['here'],
template:`<h2> {{here}} </h2>`
}
new Vue({
el:'#app',
data(){
return {
message:'不讓任何事情成為你不去學(xué)習(xí)的理由--李華明'
}
},
components:{
'world': world
}
})
</script>
</body>
</html>
嵌套的組件使用方式
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Demo</title>
<script src="https://unpkg.com/vue"></script>
</head>
<body>
<div id="app">
<world></world>
</div>
<script>
// 嵌套的子組件必須卸載父組件之上
city = {
template: `<div>我是子組件的子組件</div>`
}
//嵌套的組件
world = {
template:`
<div>
<h2>我是子組件</h2>
<city></city>
</div>`,
components:{
'city': city
}
}
new Vue({
el:'#app',
data(){
return {
message:'不讓任何事情成為你不去學(xué)習(xí)的理由--李華明'
}
},
components:{
'world': world
}
})
</script>
</body>
</html>