为什么要使用组件化编程?
传统:顶部 导航 内容 底部。四个css,html中引入。依赖关系混乱、不好维护
向外提供特定功能的js程序,一般就是一个js文件
js文件很多并且复杂
复用js,简化js的编写,提高js运行效率
实现应用中局部功能代码和资源的集合
一个界面的功能很复杂
复用编码,简化项目编码,提高运行效率
当应用中的js是以模块来编写的,这个应用就是一个模块化的应用
当应用中的js都是以模块来编写的,这个应用就是一个模块化的应用
一个文件中包含n个组件
<div id="hello">
<school>school>
<student>student>
div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止vue在启动时生成生产提示
// 1.创建组件
const school = Vue.extend({
template:`
学校名称:{{schoolName}}
学校地址:{{address}}
`,
data(){
return{
schoolName:'dada',
address:'重庆'
}
}
})
const student = Vue.extend({
template:`
学生姓名:{{studentName}}
学生年龄:{{age}}
`,
data(){
return{
studentName:'tl',
age:'11'
}
}
})
// 实例
const vm = new Vue({
el: '#hello', // 指定实例为哪个容器服务
// 2.注册组件(局部注册)
components:{
school:school,
student:student
}
});
// vue.$mount('#hello')
script>
定义一个组件:
注册组件
会导致后续组件不能渲染
<div id="hello">
<school>school>
div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止vue在启动时生成生产提示
// 1.创建组件
const student = Vue.extend({
template:`
学生姓名:{{studentName}}
学生年龄:{{age}}
`,
data(){
return{
studentName:'tl',
age:'11'
}
}
})
const school = Vue.extend({
template:`
学校名称:{{schoolName}}
学校地址:{{address}}
`,
data(){
return{
schoolName:'dada',
address:'重庆'
}
},
components:{
student
}
})
// 实例
const vm = new Vue({
el: '#hello', // 指定实例为哪个容器服务
// 2.注册组件
components:{
school
}
});
// vue.$mount('#hello')
script>
组件的标准化开发app
<div id="hello">
div>
<script type="text/javascript">
Vue.config.productionTip = false //阻止vue在启动时生成生产提示
// 1.创建组件
const student = Vue.extend({
template:`
学生姓名:{{studentName}}
学生年龄:{{age}}
`,
data(){
return{
studentName:'tl',
age:'11'
}
}
})
const school = Vue.extend({
template:`
学校名称:{{schoolName}}
学校地址:{{address}}
`,
data(){
return{
schoolName:'dada',
address:'重庆'
}
},
components:{
student
}
})
const app = Vue.extend({
template:` `,
components:{
student,
school
}
})
// 实例
const vm = new Vue({
el: '#hello', // 指定实例为哪个容器服务
template:' ',
// 2.注册组件
components:{
app
}
});
// vue.$mount('#hello')
script>
VueComponent
或者
,Vue解析时会帮我们创建school组件的实例对象,即Vue帮我们执行:new VueComponent(options)组件是可以复用的Vue实例
一个组件的data是一个函数,每个实例可以返回一个独立的data
// vue.$mount('#hello')
function Demo(){
this.a=1;
this.b=2;
}
const d = new Demo()
console.log(Demo.prototype) //显示原型属性
console.log(d.__proto__) //隐式原型属性
// 通过显示原型属性操作原型对象,追加一个x属性,值为99
d.__proto__.x=10
console.log('@',d.__proto__)
VueComponent.prototype.__proto__==Vue.prototype
一个文件中只包含有1个组件
webpack
脚手架
编写组件 .vue 包含template script style
编写App.vue,引入其他组件,将组件拼接
编写mian.js文件,new Vue() App实例
编写index.html,创建容器,引入需要的文件