24非单文件组件
非单文件组件
一、非单文件组件与单文件组件
-
非单文件组件:一个文件中可包含多个组件
-
单文件组件:一个文件只包含一个组件
二、非单文件组件
- 模板编写没有提示
- 没有构建过程, 无法将ES6 转换成 ES5
- 不支持组件的 CSS
- 真正开发中几乎不用
Vue中使用组件的三大步骤:
一、定义组件(创建组件)
二、注册组件
三、使用组件(写组件标签)
一、如何定义一个组件?
使用Vue.extend(options)创建,其中options和new Vue(options)时传入的那个options几乎一样,但也有点区别;
区别如下:
1.el不要写,为什么?—--最终所有的组件都要经过一个vm的管理,由vm中的el决定服务哪个容器。
2.data必须写成函数,为什么?-——避免组件被复用时,数据存在引用关系。
备注:使用template可以配置组件结构。
二、如何注册组件?
1.局部注册:靠new Vue的时候传入components选项
2.全局注册:靠Vue.component('组件名’,组件)
三、编写组件标签:
<school></ school>
实现
<!-- 组件:实现局部功能的代码(css,html,js)和资源(mp3,font,video...)的集合 -->
<div id="root">
<h2>{{school}}学校:</h2>
<!-- 第三步: 使用组件,通过vue components注册 组件名:组件对象-->
<school></school>
<hr>
<h2>{{student}}学生:</h2>
<!-- <student></student> -->
<student></student>
<hr>
<!-- 使用全局组件 -->
<hello></hello>
</div>
<div id="root2">
<hr>
<hello></hello>
</div>
<script>
Vue.config.productionTip = false;
// 第一步: 创建组件对象:extend 拓展延伸
const school = Vue.extend({
// el: '#root', // 组件中无需指定管理的容器,由vm管理安排组件管理,不可再组件中使用 el
// template: 模板, 配置组件的html模板
template: `
<div>
<h3>{{schoolName}}</h3>
<h3>{{schoolAddress}}</h3>
</div>
`,
// 组件必须以函数式return数据,避免对数据的引用,每次生成的组件都是一组全新的独立数据单元
data() {
return {
schoolName: 'hniu.cn',
schoolAddress: 'hnwc',
}
},
})
const student = Vue.extend({
template: `
<div>
<h3>{{studentName}}</h3>
<h3>{{studentAge}}</h3>
</div>
`,
data() {
return {
studentName: 'redskaber',
studentAge: 18,
}
},
})
const hello = Vue.extend({
template: `
<h2>{{hello}}</h2>
`,
data() {
return {
hello: 'Hello',
}
},
})
// 注册为全局组件,通过Vue.component
Vue.component('hello', hello)
const vm = new Vue({
el: '#root',
// data 还是可以自定义
data: {
school: 'Hunan IU',
student: 'Class 2004'
},
// 第二步: 组件注册,将组件交由vm所管理, component 组件,元件 {key:value} key为组件名称
components: {
// school: school,
school,
student,
},
});
// 测试 组件的全局模式
const vm2 = new Vue({
el: '#root2',
});
</script>

浙公网安备 33010602011771号