Vue组件化开发
一、Vue中使用组件的步骤
1.创建组件
Vue.extend(options),options为配置对象,与创建Vue实例的配置对象很相似,区别是data必须为函数形式。
const myHeader=Vue.extend({
template:`
<div>
<h2>我是Header</h2>
</div>
`,
data(){
}
})
2.注册组件
组件的注册有两种方式,局部注册和全局注册
局部注册:在new Vue时传入components选项(和钩子函数同级)
new Vue({
el:'#root',
components:{
//你定义的组件名:你创建组件时的名字
'app':app
}
全局注册:Vue.component(‘组件名’,组件)
Vue.component('student',student);
3.使用组件
直接使用组件标签
<body>
<div id="app">
<student></student>
<student></student>
<student></student>
</div>
</body>
二、组件的嵌套
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>vue组件化</title>
</head>
<body>
<div id="root">
<!-- 3.组件的使用 -->
<app></app>
</div>
</body>
<script src="../js/vue.js"></script>
<script>
const myHeader=Vue.extend({
template:`
<div>
<h2 style="text-align:center;">我是Header</h2>
</div>
`
})
const myMain=Vue.extend({
template:`
<div style="height:600px;">
<h2 style="text-align:center;">我是Main</h2>
</div>
`
})
const myFooter=Vue.extend({
template:`
<div>
<h2 style="text-align:center;">我是Footer</h2>
</div>
`
})
// 1.创建组件
const app=Vue.extend({
template:`
<div>
<myHeader></myHeader>
<hr>
<myMain></myMain>
<hr>
<myFooter></myFooter>
</div>
`,
components:{
myHeader,
myMain,
myFooter
}
})
// 2.组件的注册
new Vue({
el:'#root',
components:{
app
}
})
</script>
</html>