分类

  • 第三方组件
  • 自定义组件
    • 对象组件
    • vue 单文件组件
    • template 组件

局部组件 - 对象组件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
new Vue({
components:{
Layout: {
name:"Layout",
// 模板
template:'<div class="wraper"></div>',
// 组件内部状态
data(){},
// 组件外部状态
// []
// {}
props:{},
methods:{},
computed:{},
watch:{},
beforeCreate(){}
created(){}
...
}
}
})

全局组件 - 对象组件

1
2
3
4
5
6
7
8
9
10
11
12
13
import Vue from 'vue';

Vue.Component('Layout',{
name:"Layout",
template:'<div class="wraper"></div>',
data(){},
props:{},
methods:{},
computed:{},
watch:{},
beforeCreate(){}
created(){}
})

vue 单文件组件

components/comp.vue

1
2
3
4
5
6
7
8
9
10
11
<template>
<div>
this is comp page
</div>
</template>
<script>
export default {
name: "comp",
};
</script>
<style></style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<template>
<div>
<Comp/>
</div>
</template>

<script>
import Comp from '@/components/comp/.vue'
export default {
components:{
Comp
}
};
</script>

vue 模板组件

public/index.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div id="app"></div>
</body>
<template id="comp">
<div>this is comp C</div>
</template>
</html>

全局注册:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<template>
<Comp/>
</template>

<script>
import Vue from 'vue'
import Comp from '@/components/comp/.vue'
Vue.component('Comp',{
template:'#comp'
})
export default {
name:""
};
</script>

局部注册:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<template>
<Comp/>
</template>

<script>
import Comp from '@/components/comp/.vue'
export default {
components:{
Comp:{
template:"#comp"
}
}
};
</script>

props

1
2
3
4
5
6
7
8
9
10
11
12
13
//第一种
props:[]
//第二种
props:{
title:{
type:String,
required:true, //为真是必须传
default:'', //默认值
validator(n){//自定义验证规则
return //为真就不报错为假就报错,报错需要thorw new Error();
}
}
}