您的位置:首页 > 产品设计 > UI/UE

vue组件的几种书写方式

2018-03-12 22:48 766 查看
vue组件实现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>我是第一一一个tab</h1>`
}
B = {
template:`<h1>我是第二二二个tab</h1>`
}
C = {
template:`<h1>我是第三三三个tab</h1>`
}
D = {
template:`<h1>我是第四四四个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>
两个组件方式,还有一种是 .vue 为后缀的文件组件,需要模块化才能用
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Demo</title>
<script src="https://unpkg.com/vue"></script>
</head>
<body>
<div id="app">

<!-- 一个全局化组件 hello -->
<hello></hello>
<hr>
<!-- 一个局部组件 world -->
<world></world>

</div>

<script>

//注意:组件要写在实例之前,不然就会报错
Vue.component('hello',{
template:`<h1>我是一个全局话组件</h1>`
});

//局部组价 需要用components 去注册
world = {
template:`<h2>我是一个局部组件</h2>`
}
//实例
new Vue({
el:'#app',
data(){
return {}
},
//components 注册world组件
components:{
'world': world
}
})
</script>
</body>
</html>
单项数据流,父组件向子组件传参数,用props接受
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Demo</title>
<script src="https://unpkg.com/vue"></script>
</head>
<body>

<div id="app">

<!-- 一个局部组件world, 把message数据传给子组件-->

<world :here="message"></world>

</div>

<script>

world = {
// props接收父组件传过来的here
props:['here'],
template:`<h2> {{here}} </h2>`
}

new Vue({
el:'#app',
data(){
return {
message:'不让任何事情成为你不去学习的理由--李华明'
}
},
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:'不让任何事情成为你不去学习的理由--李华明'
}
},
components:{
'world': world
}
})

b0a3
</script>
</body>
</html>




欢迎关注我的个人技术公众号!javascript艺术

作者:拯救宇宙是我的使命
链接:https://www.jianshu.com/p/5757e2198304
來源:简书

欢迎关注我的个人技术公众号!javascript艺术
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  vue