Vue(2)-vue组件化编程及脚手架

课程链接

2.vue组件化编程

2.1 模块与组件、模块化与组件化

2.1.1.模块

  1. 理解: 向外提供特定功能的s 程序,一般就是一个js 文件
  2. 为什么: js 文件很多很复杂
  3. 作用: 复用js,简化js 的编写,提高 js运行效率

2.1.2.组件

  1. 理解:用来实现局部(特定)功能效果的代码集合(html/css/js/image…)
  2. 为什么: 一个界面的功能很复杂
  3. 作用:复用编码,简化项目编码,提高运行效率

传统方式编写应用:

  • 存在的问题:依赖关系混乱不好维护;代码复用率不高

适用于组件方式编写应用:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

组件:实现应用中局部功能代码资源集合

2.1.3.模块化

当应用中的js 都以模块来编写的,那这个应用就是一个模块化的应用

2.1.4.组件化

当应用中的功能都是多组件的方式来编写的,那这个应用就是一个组件化的应用。

2.2.非单文件组件

一个文件中包含有n个组件

2.2.1.基本使用

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>

    <!-- 容器 -->
    <div id="root">
        <!-- 3使用组件 -->
        <school></school>
        <hr>
        <student></student>
        <hr>
        <hello></hello>
        <hr>
    </div>
    <div id="root2">
        <hello></hello>
    </div>
</body>
<script>
    Vue.config.productionTip=false
    

    // 1创建school组件
    const school = Vue.extend({
      
      
        template:`
        <div>
            <h2>学校名称:{
       
       {schoolName}}</h2>
            <h2>学校地址:{
       
       {address}}</h2>
            <button @click="showMsg">点我提示学校信息</button>
        </div>
        `,
        data(){
      
      
            return {
      
      schoolName:'1+1',address:'武汉'}
        },methods: {
      
      
            showMsg(){
      
      
                alert(this.schoolName)
            }
        },
    })

    // 1创建student组件
    const student = Vue.extend({
      
      
        template:`
        <div>
            <h2>学生名称:{
       
       {studentName}}</h2>
            <h2>学生年龄:{
       
       {age}}</h2>    
        </div>
        `,
        data(){
      
      
            return {
      
      studentName:'brisa',age:18,}
        }
    })
    // 1创建hello组件
    const hello = Vue.extend({
      
      
        template:`
        <div>
            <h2>你好{
       
       {name}}</h2>    
        </div>
        `,
        data(){
      
      
            return {
      
      name:'ali'}
        }
    })
    // 2注册全局组件
    Vue.component('hello',hello)

    new Vue({
      
      
        el:"#root",
        data:{
      
      
            msg:'lllll',
        },
        components:{
      
      
            // 2注册组件 - 局部
            school:school,
            student,//简写
        }
    })

    
    new Vue({
      
      
        el:"#root2",
    })
</script>

2.2.2.几个注意点

几个注意点:
1.关于组件名:
一个单词组成:
第一种写法(首字母小写):school
第二种写法(首字母大写):School
多个单词组成:
第一种写法(kebab-case命名):my-school
第二种写法(CamelCase命名):MySchool (需要Vue脚手架支持)
备注:
(1).组件名尽可能回避HTML中已有的元素名称,例如:h2、H2都不行。
(2).可以使用name配置项指定组件在开发者工具中呈现的名字。

2.关于组件标签:
第一种写法:<school></school>
第二种写法:<school/>
备注:不用使用脚手架时,<school/>会导致后续组件不能渲染。

3.一个简写方式:
const school = Vue.extend(options) 可简写为:const school = options

<!-- 容器 -->
    <div id="root">
        <h1>{
   
   {msg}}</h1>
        <school></school>
        <school />
    </div>
    
</body>
<script>
    Vue.config.productionTip=false

    // 定义组件
    /* const school = Vue.extend({
        name:'atguigu',
        template:`
            <div>
                <h2>学校名:{
      
      {schoolName}}</h2>
                <h2>学校地址:{
      
      {schoolAddress}}</h2>
            </div>   
        `,
        data(){
            return {schoolName:'1+1',schoolAddress:'wuhan'}
        }
    }) */
    //简写
    const school = ({
      
      //不写vue.extend,在vm的components里也会被自动解析,这就是可以简写的原因(如果不简写,则是依靠自己的声明完成解析)
        name:'atguigu',
        template:`
            <div>
                <h2>学校名:{
       
       {schoolName}}</h2>
                <h2>学校地址:{
       
       {schoolAddress}}</h2>
            </div>   
        `,
        data(){
      
      
            return {
      
      schoolName:'1+1',schoolAddress:'wuhan'}
        }
    })


    new Vue({
      
      
        el:"#root",
        data:{
      
      
            msg:'欢迎学习vue',
        },components:{
      
      
            // 1个单词组成 - 纯小写 或者 首字母大写(与开发者工具呼应)
            // 多个单词组成 - 全部小写用-分隔 或者 首字母都大写《结合脚手架使用>
            school,//组件名,简写
        }
    })
</script>

2.2.3.嵌套

嵌套,最后容器中什么都没有写

    <!-- 容器 -->
    <div id="root">
        <!-- <api></api> -->
        
    </div>
    
</body>
<script>
    Vue.config.productionTip=false

    // 1创建student组件
    const student = Vue.extend({
      
      
        template:`
        <div>
            <h2>学生名称:{
       
       {studentName}}</h2>
            <h2>学生年龄:{
       
       {age}}</h2>    
        </div>
        `,
        data(){
      
      
            return {
      
      studentName:'brisa',age:18,}
        }
    })
    // 1创建school组件
    const school = Vue.extend({
      
      
        template:`
        <div>
            <h2>学校名称:{
       
       {schoolName}}</h2>
            <h2>学校地址:{
       
       {address}}</h2>
            <student></student>
        </div>
        `,
        data(){
      
      
            return {
      
      schoolName:'1+1',address:'武汉'}
        },components:{
      
      
            student//school中嵌套student,要使用的话,就在这里的template加student
        }
    })
    const hello = Vue.extend({
      
      
        template:'<h3>hello,{
      
      {name}}哇</h3>',
        data(){
      
      return {
      
      name:'brisa'}}
    })
    const api = Vue.extend({
      
      //使用一个api管理所有的组件
        template:`
            <div>
                <school></school>
                <hello></hello>
            </div>
        `,components:{
      
      
            school,
            hello
        }
    })
    new Vue({
      
      
        template:`<api></api>`,//在这里使用api,不在容器中去写
        el:"#root",
        data:{
      
      
            
        },
        components:{
      
      
            api//vm就只调用这个api即可
        }

    })
</script>

2.2.4.理解VueComponent

关于VueComponent:
1.school组件本质是一个名为VueComponent的构造函数,且不是程序员定义的,是Vue.extend生成的。

2.我们只需要写<school/><school></school>,Vue解析时会帮我们创建school组件的实例对象,
即Vue帮我们执行的:new VueComponent(options)

3.特别注意:每次调用Vue.extend,返回的都是一个全新的VueComponent!!!!

4.关于this指向:
(1).组件配置中:
data函数、methods中的函数、watch中的函数、computed中的函数 它们的this均是VueComponent实例对象
(2).new Vue(options)配置中:
data函数、methods中的函数、watch中的函数、computed中的函数 它们的this均是Vue实例对象

5.VueComponent的实例对象,以后简称vc(也可称之为:组件实例对象)。
Vue的实例对象,以后简称vm。

<!-- 容器 -->
    <div id="root">
      <!-- <api></api> -->
    </div>
  </body>
  <script>
    Vue.config.productionTip = false;

    // 1创建school组件
    const school = Vue.extend({
      
      
      template: `
        <div>
            <h2>学校名称:{
       
       {schoolName}}</h2>
            <h2>学校地址:{
       
       {address}}</h2>
            <button @click='showName'>点我提示学校名</button>
        </div>
        `,
      data() {
      
      
        return {
      
       schoolName: "1+1", address: "武汉" };
      },
      methods: {
      
      
        showName() {
      
      
          alert(this.schoolName);
          console.log(this); //this--->vc(VueComponent)的school实例对象
        },
      },
    });

    const hello = Vue.extend({
      
      
      template: `
        <div>
            <h2>你好,{
       
       {name}}</h2>
        </div>
        `,
      data() {
      
      
        return {
      
       name: "brisa" };
      },
    });

    console.log(school === hello); //false
    console.log(school);
    /* ƒ VueComponent(options) {
              this._init(options);
          } */
    const api = Vue.extend({
      
      
      template: `
            <div>
                <school></school>
                <hello></hello>
            </div>
        `,
      components: {
      
      
        school,
        hello,
      },
    });
    const vm = new Vue({
      
      
      template: `<api></api>`,
      el: "#root",
      data: {
      
      },
      components: {
      
      
        api,
      },
    });

    console.log(vm);
  </script>

2.2.5.一个重要的内置关系

显示原型属性:prototype
隐式原型属性:__proto__
指向的对象称为原型对象

1.一个重要的内置关系:VueComponent.prototype.__proto__ === Vue.prototype
2.为什么要有这个关系:让组件实例对象(vc)可以访问到 Vue原型上的属性、方法
在这里插入图片描述

2.3.单文件组件

一个文件中只包含有1个组件

2.3.1.一个.vue文件的组成(三部分)

<!-- 1.模板页面 -->
<template>
	页面模板
</template>
<!--2. JS 模块对象 -->
<script>
	export default {
      
      
		data() {
      
      
			return {
      
      }
			}, 
		methods: {
      
      }, 
		computed: {
      
      }, 
		components: {
      
      }
	}
</script>
<!--3. 样式 -->
<style>
	样式定义
</style>

2.3.2.基本使用

  1. 引入组件
    先写好xxx.vue的组件,然后再App.vue中import该组件,并在App中的components添加它。
  2. 映射成标签
  3. 使用组件标签
<template>
  <div>
    <school></school>
    <Student></Student>
  </div>
</template>

<script>
// 引入组件
import School from "./School";
import Student from "./Student";
export default {
      
      
  name: "App",
  components: {
      
      
    School,
    Student,
  },
};
</script>

<!-- <style>
</style> -->

3.使用VUE脚手架

3.1.初始化脚手架

1、第一步(仅第一次执行):全局安装@vue/cli。

  • npm install -g @vue/cli
    2、第二步:切换到你要创建项目的目录,然后使用命令创建项目
  • vue create xxxx
    3、第三步:启动项目
  • npm run serve
    备注:
  1. 如出现下载缓慢请配置 npm 淘宝镜像:npm config set registry https://registry.npm.taobao.org
  2. Vue 脚手架隐藏了所有 webpack 相关的配置,若想查看具体的 webpakc 配置,
    请执行:vue inspect > output.js

3.2.脚手架文件结构

├── node_modules 
├── public
│   ├── favicon.ico: 页签图标
│   └── index.html: 主页面
├── src
│   ├── assets: 存放静态资源
│   │   └── logo.png
│   │── component: 存放组件
│   │   └── HelloWorld.vue
│   │── App.vue: 汇总所有组件
│   │── main.js: 入口文件
├── .gitignore: git版本管制忽略的配置
├── babel.config.js: babel的配置文件
├── package.json: 应用包配置文件 
├── README.md: 应用描述文件
├── package-lock.json:包版本控制文件

3.3.关于不同版本的Vue

  1. vue.js与vue.runtime.xxx.js的区别:
    1. vue.js是完整版的Vue,包含:核心功能 + 模板解析器。
    2. vue.runtime.xxx.js是运行版的Vue,只包含:核心功能;没有模板解析器。
  2. 因为vue.runtime.xxx.js没有模板解析器,所以不能使用template这个配置项,需要使用render函数接收到的createElement函数去指定具体内容。

3.4.vue.config.js配置文件

  1. 使用vue inspect > output.js可以查看到Vue脚手架的默认配置。
  2. 使用vue.config.js可以对脚手架进行个性化定制,详情见:https://cli.vuejs.org/zh

3.5.ref属性

  1. 被用来给元素或子组件注册引用信息(id的替代者)
  2. 应用在html标签上获取的是真实DOM元素,应用在组件标签上是组件实例对象(vc)
  3. 使用方式:
    1. 打标识:<h1 ref="xxx">.....</h1><School ref="xxx"></School>
    2. 获取:this.$refs.xxx

3.6.props配置项

  1. 功能:让组件接收外部传过来的数据

  2. 传递数据:<Demo name="xxx"/>

  3. 接收数据:

    1. 第一种方式(只接收):props:['name']

    2. 第二种方式(限制类型):props:{name:String}

    3. 第三种方式(限制类型、限制必要性、指定默认值):

      props:{
              
              
      	name:{
              
              
      	type:String, //类型
      	required:true, //必要性
      	default:'老王' //默认值
      	}
      }
      

    备注:props是只读的,Vue底层会监测你对props的修改,如果进行了修改,就会发出警告,若业务需求确实需要修改,那么请复制props的内容到data中一份,然后去修改data中的数据。

3.7.mixin(混入)

  1. 功能:可以把多个组件共用的配置提取成一个混入对象

  2. 使用方式:

    第一步定义混合:

    {
        data(){....},
        methods:{....}
        ....
    }
    

    第二步使用混入:

    ​ 全局混入:Vue.mixin(xxx)
    ​ 局部混入:mixins:['xxx']

3.8.插件

  1. 功能:用于增强Vue

  2. 本质:包含install方法的一个对象,install的第一个参数是Vue,第二个以后的参数是插件使用者传递的数据

  3. 定义插件:

    对象.install = function (Vue, options) {
          
          
        // 1. 添加全局过滤器
        Vue.filter(....)
    
        // 2. 添加全局指令
        Vue.directive(....)
    
        // 3. 配置全局混入(合)
        Vue.mixin(....)
    
        // 4. 添加实例方法
        Vue.prototype.$myMethod = function () {
          
          ...}
        Vue.prototype.$myProperty = xxxx
    }
    
  4. 使用插件:Vue.use()

3.9.scoped样式

  1. 作用:让样式在局部生效,防止冲突。
  2. 写法:<style scoped>

题外话:
vue脚手架不直接支持less,用 npm i less-loader@7 下载安装依赖
这个@7是限制版本
<style lang="less"></style>

3.10.总结TodoList案例

  1. 组件化编码流程:

    ​ (1).拆分静态组件:组件要按照功能点拆分,命名不要与html元素冲突。

    ​ (2).实现动态组件:考虑好数据的存放位置,数据是一个组件在用,还是一些组件在用:

    ​ 1).一个组件在用:放在组件自身即可。

    ​ 2). 一些组件在用:放在他们共同的父组件上(状态提升)。

    ​ (3).实现交互:从绑定事件开始。

  2. props适用于:

    ​ (1).父组件 ==> 子组件 通信

    ​ (2).子组件 ==> 父组件 通信(要求父先给子一个函数)

  3. 使用v-model时要切记:v-model绑定的值不能是props传过来的值,因为props是不可以修改的!

  4. props传过来的若是对象类型的值,修改对象中的属性时Vue不会报错,但不推荐这样做。

3.11.webStorage

  1. 存储内容大小一般支持5MB左右(不同浏览器可能还不一样)

  2. 浏览器端通过 Window.sessionStorageWindow.localStorage 属性来实现本地存储机制。

  3. 相关API:

    1. xxxxxStorage.setItem('key', 'value');
      该方法接受一个键和值作为参数,会把键值对添加到存储中,如果键名存在,则更新其对应的值。

    2. xxxxxStorage.getItem('person');

      ​ 该方法接受一个键名作为参数,返回键名对应的值。

    3. xxxxxStorage.removeItem('key');

      ​ 该方法接受一个键名作为参数,并把该键名从存储中删除。

    4. xxxxxStorage.clear()

      ​ 该方法会清空存储中的所有数据。

  4. 备注:

    1. SessionStorage存储的内容会随着浏览器窗口关闭而消失
    2. LocalStorage存储的内容,需要手动清除才会消失
    3. xxxxxStorage.getItem(xxx)如果xxx对应的value获取不到,那么getItem的返回值是null
    4. JSON.parse(null)的结果依然是null

3.12.组件的自定义事件

  1. 一种组件间通信的方式,适用于:子组件 ===> 父组件

  2. 使用场景:A是父组件,B是子组件,B想给A传数据,那么就要在A中给B绑定自定义事件(事件的回调在A中)。

  3. 绑定自定义事件:

    1. 第一种方式,在父组件中:<Demo @atguigu="test"/><Demo v-on:atguigu="test"/>

    2. 第二种方式,在父组件中:

      <Demo ref="demo"/>
      ......
      mounted(){
              
              
         this.$refs.xxx.$on('atguigu',this.test)
      }
      
    3. 若想让自定义事件只能触发一次,可以使用once修饰符,或$once方法。

  4. 触发自定义事件:this.$emit('atguigu',数据)

  5. 解绑自定义事件this.$off('atguigu')

  6. 组件上也可以绑定原生DOM事件,需要使用native修饰符。

  7. 注意:通过this.$refs.xxx.$on('atguigu',回调)绑定自定义事件时,回调要么配置在methods中,要么用箭头函数,否则this指向会出问题!

3.13.全局事件总线(GlobalEventBus)

  1. 一种组件间通信的方式,适用于任意组件间通信。

  2. 安装全局事件总线:

    new Vue({
          
          
    	......
    	beforeCreate() {
          
          
    		Vue.prototype.$bus = this //安装全局事件总线,$bus就是当前应用的vm
    	},
        ......
    }) 
    
  3. 使用事件总线:

    1. 接收数据:A组件想接收数据,则在A组件中给$bus绑定自定义事件,事件的回调留在A组件自身。

      methods(){
              
              
        demo(data){
              
              ......}
      }
      ......
      mounted() {
              
              
        this.$bus.$on('xxxx',this.demo)
      }
      
    2. 提供数据:this.$bus.$emit('xxxx',数据)

  4. 最好在beforeDestroy钩子中,用$off去解绑当前组件所用到的事件。

3.14.消息订阅与发布(pubsub)

  1. 一种组件间通信的方式,适用于任意组件间通信。

  2. 使用步骤:

    1. 安装pubsub:npm i pubsub-js

    2. 引入: import pubsub from 'pubsub-js'

    3. 接收数据:A组件想接收数据,则在A组件中订阅消息,订阅的回调留在A组件自身。

      methods(){
              
              
        demo(data){
              
              ......}
      }
      ......
      mounted() {
              
              
        this.pid = pubsub.subscribe('xxx',this.demo) //订阅消息
      }
      
    4. 提供数据:pubsub.publish('xxx',数据)

    5. 最好在beforeDestroy钩子中,用PubSub.unsubscribe(pid)去取消订阅。

3.15.nextTick

  1. 语法:this.$nextTick(回调函数)
  2. 作用:在下一次 DOM 更新结束后执行其指定的回调。
  3. 什么时候用:当改变数据后,要基于更新后的新DOM进行某些操作时,要在nextTick所指定的回调函数中执行。

3.16.Vue封装的过度与动画

  1. 作用:在插入、更新或移除 DOM元素时,在合适的时候给元素添加样式类名。

  2. 图示:
    在这里插入图片描述

  3. 写法:

    1. 准备好样式:

      • 元素进入的样式:
        1. v-enter:进入的起点
        2. v-enter-active:进入过程中
        3. v-enter-to:进入的终点
      • 元素离开的样式:
        1. v-leave:离开的起点
        2. v-leave-active:离开过程中
        3. v-leave-to:离开的终点
    2. 使用<transition>包裹要过度的元素,并配置name属性:

      <transition name="hello">
      	<h1 v-show="isShow">你好啊!</h1>
      </transition>
      
    3. 备注:若有多个元素需要过度,则需要使用:<transition-group>,且每个元素都要指定key值。

猜你喜欢

转载自blog.csdn.net/m0_43416592/article/details/129640299