一 非单文件组件
组件不是一个单独的vue文件,同时多个组件定义在一个文件当中,这样的写法在实际开发中不常使用。
关于 VueComponent:
1、school组件本质上是一个名为VueComponent的构造函数,且不是程序员定义的,是Vue.extend生成
2、我们只需要写
3、每次调用Vue.extend,返回都是一个全新的 VueComponent
4、关于 this 指向:
(1)组件配置当中:data函数,methods中的函数,watch中的函数,computed中的函数,它们的指向均是【VC对象】
(2)new Vue(options)配置中:data函数,methods中的函数,watch中的函数,computed中的函数,是【VM对象】
5、VueComponent的实例对象,简称:vc。Vue的实例对象,简称:vm
<!-- 容器,绑定vue --><div id="app"><school></school><hr><student></student><hr><halo></halo></div><script>Vue.config.productionTip = false// 创建组件const school = Vue.extend({data() {return {schoolName: '麻省',schoolAddr: '广州'}},/*** 这里的template里面的标签需要使用一个div进行包裹起来*/template: `<div><h2>学校名称:{{ schoolName }}</h2><h2>学校地址:{{ schoolAddr }}</h2></div>`})// 创建组件const student = Vue.extend({data() {return {studentName: 'lz',studentAge: 19}},template: `<div><h3>学生姓名:{{ studentName }}</h3><h4>学生年龄 {{ studentAge }}</h4></div>`})const halo = Vue.extend({template: `<div>你好!</div>`})// 全局注册组件的方式,会将当前这个组件注册进所有的VM实例对象当中Vue.component('halo', halo)// 第一步:创建vue对象const vm = new Vue({el: "#app",data: {name: "lz"},// 第二步:注册组件,将已经创建好的组件放在这里进行注册// 这里是 局部注册components: {school: school,student: student}})</script>
1.1 组件嵌套
<!-- 容器,绑定vue --><div id="app"><school></school><hr></div><script>Vue.config.productionTip = false// 创建组件const student = Vue.extend({data() {return {studentName: 'lz',studentAge: 19}},template: `<div><h3>学生姓名:{{ studentName }}</h3><h4>学生年龄 {{ studentAge }}</h4></div>`})// 创建组件const school = Vue.extend({data() {return {schoolName: '广工',schoolAddr: '广州'}},/*** 在 school 组件当中,注册进 student 组件* 然后在 div 中进行调用*/template: `<div><h2>学校名称:{{ schoolName }}</h2><h2>学校地址:{{ schoolAddr }}</h2><student></student></div>`,components: {student}})// 第一步:创建vue对象const vm = new Vue({el: "#app",data: {name: "lz"},// 第二步:注册组件,将已经创建好的组件放在这里进行注册// 这里是 局部注册components: {school}})</script>
二 单文件组件
这里定义了很多个文件,在实际开发中常用
这些文件并不能直接被浏览器进行解析执行,需要放置在vue脚手架中才能进行读取
1丶main.js
import App from './App'new Vue({el: '#app',components: {App},template: `<App></App>`,data() {return {}}})
2丶index.html
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><title>单文件组件语法</title></head><body><!--浏览器不能直接解析ES6语法--><div id="app"></div><script src="../../js/vue.js"></script><script src="./main.js"></script></body></html>
3丶School.vue
<template><div><h3>学校名称:{{ name }}</h3><h3>学校地址:{{ addr }}</h3><button @click="say"></button></div></template><script>/*** 默认暴露,跟ES6的模块化有关系*/export default {name: "School",data() {return {name: '广工',addr: '广州'}},methods: {say() {console.log('I from : ', this.name)}},component: {}}</script><style scoped></style>
4丶App.vue
<template><div><School></School></div></template><script>import School from './School'export default {name: "App",// 注册组件components: {School}}</script><style scoped></style>
