提示:该文章为笔者的个人笔记并不是权威,如有错误,谢谢指出。
非单文件组件
一、 基本使用
组件局部注册
<div id="root">
// 使用组件
<school></school>
<hr>
<student></student>
<hr>
</div>
<script>
// 注册组件
const school = Vue.extend({
data() {
return {
schoolName : 'lyun',
address: '福建'
}
},
methods: {
showName() {
alert(11)
}
},
template: `
<div>
<h2>学校名称:{{schoolName}}</h2>
<button @click="showName">点我提示学校名</button>
<h2>学校地址:{{address}}</h2>
</div>
`,
})
const student = Vue.extend({
data() {
return {
studentName: '小爱同学',
age: 18
}
},
template:`
<div>
<h2>学生名称:{{studentName}}</h2>
<h2>学生年龄:{{age}}</h2>
</div>
`,
})
new Vue({
el: '#root',
// 注册组件 (局部注册)
components: {
school:school,
student:student
}
})
</script>
组件全局注册
<div id="root2">
<hello></hello>
</div>
<script>
// 创建组件
const hello = Vue.extend({
data() {
return {
name: '小爱同学',
}
},
template: `
<div>
<h2>你好,{{name}}</h2>
</div>
`
})
// 全局注册
Vue.component('hello', hello)
new Vue({
el: '#root2',
})
</script>
- 使用组件三大步骤:创建组件、注册组件、使用组件
- 注册组件分为全局注册和局部注册
- 局部注册:new Vue的时候传入components选项
- 全局注册:Vue.component('组件名', 组件)
- 使用Vue.extend(options)创建,其中options和new Vue(options)时传入的那个options几乎一样
- el不要写 --- 最终所有的组件都要经过一个vm管理,有vm决定那个容器
- data必须写成函数 --- 避免组件被复用,数据存在引用关系
二、 组件嵌套
<div id="root">
<app></app>
</div>
<script>
// 创建组件
const student = Vue.extend({
data() {
return {
studentName: '小爱同学',
age: 18
}
},
template:`
<div>
<h2>学生名称:{{studentName}}</h2>
<h2>学生年龄:{{age}}</h2>
</div>
`,
})
// 创建组件
const school = Vue.extend({
data() {
return {
schoolName : 'lyun',
address: '福建'
}
},
methods: {
showName() {
alert(11)
}
},
template: `
<div>
<h2>学校名称:{{schoolName}}</h2>
<button @click="showName">点我提示学校名</button>
<h2>学校地址:{{address}}</h2>
<student></student>
</div>
`,
components: {
student: student
}
})
const hello = Vue.extend({
template:`
<div>
<h2>{{news}}</h2>
</div>
`,
data() {
return {
news: '你好',
}
},
})
const app = Vue.extend({
template:`
<div>
<school></school>
<hello></hello>
</div>
`,
components: {
school:school,
hello:hello,
}
})
new Vue({
el: '#root',
// 注册组件 (局部注册)
components: {
app:app
}
})
</script>
三、 关于VueComponent
- school组件本质是一个名为VueComponent的构造函数,且不是程序员定义的,是Vue.extend生成的
- 我们只需要写<school/> 或 <school></school>,Vue解析时会帮助我们创建school组件的实例对象即Vue帮我们执行: new VueComponent(options)
- 一个重要的内置关系:VueComponent.prototype.__proto__ === Vue.ptototype