Vue 基础快速入门(二)

Vue 组件化编程

模块, 组件, 模块化与组件化

模块

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

组件

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

模块化

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

组件化

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

非单文件组件

  1. 模板编写没有提示
  2. 没有构建过程,无法将 ES6 转换成 ES5
  3. 不支持组件的 CSS
  4. 真正开发中几乎不用

基本使用

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> <student></student> <hello></hello>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>基本使用</title>
        <script type="text/javascript" src="../js/vue.js"></script>
    </head>
    <body>
        <div id="root">
            <hello></hello>
            <hr>
            <h1>{{msg}}</h1>
            <hr>
            <!-- 第三步:编写组件标签 -->
            <school></school>
            <hr>
            <!-- 第三步:编写组件标签 -->
            <student></student>
            <student></student>
        </div>
        <div id="root2">
            <hello></hello>
        </div>
    </body>
    <script type="text/javascript">
        //第一步:创建school组件
        const school1 = Vue.extend({
            // el:'#root', //组件定义时,不写el配置项,因为最终所有的组件都要被一个vm管理,由vm决定服务于哪个容器。
            template: `
<div class="demo">
<h2>学校名称:{{schoolName}}</h2>
<h2>学校地址:{{address}}</h2>
<button @click="showName()">点我提示学校名</button>	
        </div>
`,
            data() {//写成函数
                return {
                    schoolName: '尚硅谷',
                    address: '北京昌平'
                }
            },
            methods: {
                showName() {
                    alert(this.schoolName)
                }
            },
        })
        //第一步:创建student组件
        const student1 = Vue.extend({
            template: `
<div>
<h2>学生姓名:{{studentName}}</h2>
<h2>学生年龄:{{age}}</h2>
        </div>
`,
            data() {
                return {
                    studentName: '张三',
                    age: 18
                }
            }
        })
        //第一步:创建hello组件
        const hello1 = Vue.extend({
            template: `
<div>	
<h2>你好啊!{{name}}</h2>
        </div>
`,
            data() {
                return {
                    name: 'Tom'
                }
            }
        })

        //第二步:全局注册组件
        Vue.component('hello', hello1)
        //创建vm
        new Vue({
            el: '#root',
            data: {
                msg: '你好啊!'
            },
            //第二步:注册组件(局部注册)
            components: {
                school: school1,
                student: student1
                // 组件名:中转变量,如果组件名和中转变量一致如school:school则可以写为school
            }
        })
        new Vue({
            el: '#root2',
        })
    </script>
</html>

注意点

几个注意点:
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

组件的嵌套

子组件要在父组件之前定义

管理所有组件 app

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>组件的嵌套</title>
        <!-- 引入Vue -->
        <script type="text/javascript" src="../js/vue.js"></script>
    </head>

    <body>
        <!-- 准备好一个容器-->
        <div id="root">
        </div>
    </body>
    <script type="text/javascript">
        Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
        //定义student组件
        const student = Vue.extend({
            name: 'student',
            template: `
<div>
<h2>学生姓名:{{name}}</h2>	
<h2>学生年龄:{{age}}</h2>	
        </div>
`,
            data() {
                return {
                    name: 'pink老师',
                    age: 18
                }
            }
        })
        //定义school组件
        const school = Vue.extend({
            name: 'school',
            template: `
<div>
<h2>学校名称:{{name}}</h2>	
<h2>学校地址:{{address}}</h2>	
<student></student>
        </div>
`,
            data() {
                return {
                    name: '尚硅谷',
                    address: '北京'
                }
            },
            //注册组件(局部)
            components: {
                student
            }
        })
        //定义hello组件
        const hello = Vue.extend({
            template: `<h1>{{msg}}</h1>`,
            data() {
                return {
                    msg: '欢迎来到尚硅谷学习!'
                }
            }
        })
        //定义app组件
        const app = Vue.extend({
            template: `
<div>	
<hello></hello>
<school></school>
        </div>
`,
            components: {
                school,
                hello
            }
        })
        //创建vm
        new Vue({
            template: '<app></app>',
            el: '#root',
            //注册组件(局部)
            components: { app }
        })
    </script>
</html>

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的实例对象管理着 vc

重要的内置关系

  1. 一个重要的内置关系:VueComponent.prototype.__proto__ === Vue.prototype
  2. 为什么要有这个关系:让组件实例对象 (vc) 可以访问到 Vue 原型上的属性、方法
Vue 构造函数:
Vue 构造函数的 prototype 是 Vue 的原型对象

vm(Vue构造函数构造的实例对象):
vm 对象的原型等于其构造函数的 prototype,即是 Vue 的 prototype, 即指向 Vue 的原型对象:vm.__proto__===Vue.prototype

Vue的原型对象的原型:
即 Vue.prototype.__proto__ 等于其构造函数的 prototype:Vue.prototype.__proto__===Object.prototype

VueComponent 构造函数:
VueComponent 构造函数的 prototype 是 VueComponent 的原型对象

vc(VueComponent构造函数构造的实例对象):
vc对象的原型等于其构造函数的 prototype, 即是 VueComponent 的prototype, 即指向 VueComponent 的原型对象:

最后,强行改变 VueComponent 原型对象的.__proto__指向,让其指向从 Object 原型对象到 Vue 的原型对象
VueComponent.prototype.__proto__ === Vue.prototype
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>一个重要的内置关系</title>
        <!-- 引入Vue -->
        <script type="text/javascript" src="../js/vue.js"></script>
    </head>
    <body>
        <!-- 准备好一个容器-->
        <div id="root">
            <school></school>
        </div>
    </body>

    <script type="text/javascript">
        Vue.config.productionTip = false //阻止 vue 在启动时生成生产提示。
        Vue.prototype.x = 99

        //定义school组件
        const school = Vue.extend({
            name: 'school',
            template: `
<div>
<h2>学校名称:{{name}}</h2>	
<h2>学校地址:{{address}}</h2>	
<button @click="showX">点我输出x</button>
        </div>
`,
            data() {
                return {
                    name: '尚硅谷',
                    address: '北京'
                }
            },
            methods: {
                showX() {
                    console.log(this.x)
                }
            },
        })
        console.log(school.prototype.__proto__ === Vue.prototype)
        console.dir(school)

        //创建一个vm
        const vm = new Vue({
            el: '#root',
            data: {
                msg: '你好'
            },
            components: { school }
        })
        //定义一个构造函数
        /*	function Demo() {
			this.a = 1
			this.b = 2
		}
		//创建一个Demo的实例对象
		const d = new Demo()
		console.log(Demo.prototype) //显式原型属性,只有函数拥有
		// 这两个原型属性的地址都指向原型对象
		console.log(d.__proto__) //隐式原型属性,对象拥有
		console.log(Demo.prototype === d.__proto__)
		//程序员通过显示原型属性操作原型对象,追加一个x属性,值为99
		Demo.prototype.x = 99
		// 顺着这条线放东西
		console.log("输出:", d.__proto__.x)
		// 顺着这条线取东西

		console.log('@', d)
	*/
    </script>
</html>

单文件组件

文件命名: 单个单词: School.vue 多个单词: MySchool.vue

VSCode 安装 Vetur 插件

School.vue文件

<template>
    <!-- 必须有一个根标签 -->
    <div class="demo">
        <h2>学校名称:{{ name }}</h2>
<h2>学校地址:{{ address }}</h2>
<button @click="showName">点我提示学校名</button>
</div>
</template>
//  <v 加enter能够快速生成模板
<script>
    export default Vue.extend({ //可省略Vue.extend()
name:'School',//定义Chrome工具栏Vue工具组件名称
    data(){
    return {
        name:'尚硅谷',
        address:'北京昌平'
    }
},
    methods: {
        showName(){
            alert(this.name)
        }
    },
})
</script>
<style>
        .demo{
            background-color: orange;
        }
</style>

Student.vue文件

<template>
	<div>
		<h2>学生姓名:{{name}}</h2>
		<h2>学生年龄:{{age}}</h2>
	</div>
</template>

<script>
	 export default {
		name:'Student',
		data(){
			return {
				name:'张三',
				age:18
			}
		}
	}
</script>

App.vue文件

// 创建一个App.vue文件汇总其余组件,将其余vue中创建的组件注册并且编写组件标签
<template>
    <div>
        <School></School>
        <Student></Student>
        <!-- 编写组件标签 -->
    </div>
</template>
<script>
    //引入组件
    import School from "./School.vue";
    import Student from "./Student.vue";
    export default {
        name: "App",
        components: {
            //注册组件
            School,
            Student,
        },
    };
</script>

main.js文件

import App from './App.vue'
// 在main.js文件中创建vue实例vm,并引入最高级的App.vue文件
new Vue({
	el: '#root',
	template: `<App></App>`,
	components: { App },
})

index.html文件,准备一个容器

<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8" />
	<title>练习一下单文件组件的语法</title>
</head>
<body>
	<!-- 准备一个容器 -->
	<div id="root"></div>
        //引入script标签在body的最下方,并且优先引入Vue
	<script type="text/javascript" src="../js/vue.js"></script>
	<script type="text/javascript" src="./main.js"></script>
</body>
</html>

Vue 脚手架

  • Vue脚手架是Vue官方提供的标准化开发工具(开发平台).
  • 最新的版本是4.x.
  • 文档

步骤

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

npm install -g @vue/cli
# 或
yarn global add @vue/cli

第二步 切换到创建项目的目录, 使用命令创建项目

vue create xxx
  • vue2
  • vue3
  • 自定义

babel : ES6 ===> ES5
eslint : 语法检查 第三步: 启动项目

第三步 启动项目

npm run server
// OR
yarn serve
// 查看版本
vue --version

备注:

  • 下载缓慢请配置 npm 淘宝镜像

    npm config set registry https://registry.npm.taobao.org
    
  • Vue 脚手架隐藏了所有 webpack 相关的配置, 若想查看具体的 webpakc 配置, 请执行

    vue inspect > output.js
    

分析脚手架文件结构

├── 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:包版本控制文件

关于不同版本的 Vue

vue.js 与v ue.runtime.xxx.js 的区别:

  1. vue.js 是完整版的 Vue,包含:核心功能 + 模板解析器
  2. vue.runtime.xxx.js 是运行版的 Vue,只包含:核心功能;没有模板解析器

因为 vue.runtime.xxx.js 没有模板解析器,所以不能使用 template 这个配置项,需要使用 render 函数接收到的 createElement 函数去指定具体内容

实践: 总是使用非完整版,然后配合 vue-loader 和 vue 文件

  • 保证用户体验,用户下载的 js 文件体积更小,但只支持 h 函数.
  • 保证开发体验,开发者可以直接在 vue 里面写 HTML 标签,而不写 h 函数.
  • vue-loader 可以把 vue 文件里的 HTML,转为 h 函数

vue.config.js 配置文件

  1. 使用 vue inspect > output.js 可以查看到 Vue 脚手架的默认配置,但无法更改。文件标红最外面加上const a = {},在 output.js 文件中
  2. 在根目录建立vue.config.js文件可以对脚手架进行个性化定制,详情见: 配置参考 | Vue CLI (vuejs.org)

脚手架构建的 index.html 文件

<!DOCTYPE html>
<html lang="">
    <head>
        <meta charset="utf-8">
        <!-- 针对IE浏览器的一个特殊配置,含义是让IE浏览器以最高的渲染级别渲染页面 -->
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <!-- 开启移动端的理想视口 -->
        <meta name="viewport" content="width=device-width,initial-scale=1.0">
        <!-- 配置页签图标 <%= BASE_URL %>代替./是当前目录下的图标-->
        <link rel="icon" href="<%= BASE_URL %>favicon.ico">
        <!-- 引入第三方样式 -->
        <link rel="stylesheet" href="<%= BASE_URL %>css/bootstrap.css">
        <!-- 配置网页标题 -->
        <title>硅谷系统</title>
    </head>

    <body>
        <!-- 当浏览器不支持js时noscript中的元素就会被渲染 -->
        <noscript>
            <strong>We're sorry but <%= htmlWebpackPlugin.options.title %> doesn't work properly without JavaScript enabled.
                Please enable it to continue.</strong>
                </noscript>
            <!-- 容器 -->
            <div id="app"></div>
            <!-- built files will be auto injected -->
            </body>
        </html>

main.js

/* 
  该文件是整个项目的入口文件
*/
//引入Vue
// import Vue from 'vue/dist/vue'
//引入完整版
import Vue from 'vue'
// 引入运行时版本
//引入App组件,它是所有组件的父组件
import App from './App.vue'
//关闭vue的生产提示
Vue.config.productionTip = false
/* 
  关于不同版本的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函数去指定具体内容。
*/

//创建Vue实例对象---vm
new Vue({
    el: '#app',
    /*
  render(createElement) {
    return createElement('h1', '你好啊')
    // return console.log(typeof createElement);
    // 打印出的createElement是函数
  },
  简写:
    render:createElement=>createElement('h1', '你好啊'),
  再简化:
    render:q=> q('h1','你好啊')
  */

    //render函数完成了这个功能:将App组件放入容器中
    render: h => h(App),

    // template: `<App></App>`, 运行版本的vue, main.js不能写模板
    // components: { App },
})

ref 属性

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

App.vue

<template>
    <div>
        <h1 v-text="msg" ref="title"></h1>
        <button ref="btn" @click="showDOM">点我输出上方的DOM元素</button>
        <School ref="sch"/>
    </div>
</template>

<script>
    //引入School组件
    import School from './components/School'

    export default {
        name:'App',
        components:{School},
        data() {
            return {
                msg:'欢迎学习Vue!'
            }
        },
        methods: {
            showDOM(){
                console.log(this.$refs.title) //真实DOM元素
                console.log(this.$refs.btn) //真实DOM元素
                console.log(this.$refs.sch) //School组件的实例对象(vc)
            }
        },
    }
</script>

props 配置项

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

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

接收数据:

  1. 第一种方式 (只接收):props:['name']
  2. 第二种方式 (限制类型):props:{name:String}
  3. 第三种方式 (限制类型、限制必要性、指定默认值) :
props:{
    name:{
        type:String, //类型
        required:true, //必要性
        default:'老王' //默认值
    }
}

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

props 中接收的数据会被绑定到组件实例对象 vc 上,且优先级高于 data 中的数据,data 中的数据属性名字不能与接收的 props 属性名一致

页面中学生年龄点击增加,控制台中 data 中的属性 myAge 改变,props 中 age 属性不变

App.vue

<template>
    <div>
        <!-- 在组件标签中声明传入属性 
:即v-bind 将字符串18变为js表达式,使其可以接受加法运算
-->
        <Student name="李四" sex="" :age="18" />
    </div>
</template>
<script>
    import Student from "./components/Student";
    export default {
        name: "App",
        components: { Student },
    };
</script>

Student.vue

<template>
    <div>
        <h1>{{ msg }}</h1>
        <h2>学生姓名:{{ name }}</h2>
        <h2>学生性别:{{ sex }}</h2>
        <h2>学生年龄:{{ myAge + 1 }}</h2>
        <button @click="updateAge">尝试修改收到的年龄</button>
    </div>
</template>

<script>
    export default {
        name: "Student",
        data() {
            console.log(this);
            return {
                msg: "我是一个尚硅谷的学生",
                myAge: this.age,
                //   props的数据不允许修改,想要改动得到propo的数据放入data中
                //   props的优先级高,data中的this.age是props中接收的数据
            };
        },
        methods: {
            updateAge() {
                this.myAge++;
            },
        },
        //方法一:简单声明接收,放在组件实例对象vc上
        // props:['name','age','sex']

        //方法二:接收的同时对数据进行类型限制,类型如果不符合报错
        /* props:{
			name:String,
			age:Number,
			sex:String
		} */

        //方法三:接收的同时对数据:进行类型限制+默认值的指定+必要性的限制
        props: {
            name: {
                type: String, //name的类型是字符串
                required: true, //name是必要的,有此属性一般不需要加默认值
            },
            age: {
                type: Number,
                default: 99, //默认值,即如果不传此属性则使用默认值
            },
            sex: {
                type: String,
                required: true,
            },
        },
    };
</script>

mixin (混入)

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

使用方式:

第一步定义混合:

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

第二步使用混入:

使用前需要import导入

全局混入:Vue.mixin(xxx)放在 main.js 文件中,所有 vm, vc 都能得到混入的属性

局部混入:mixins:['xxx']放在需要的文件中,在此文件中得到混入的属性

如果混入与自身有同名属性,自身属性优先级高,会覆盖掉混入属性

School.vue

<template>
    <div>
        <h2 @click="showName">学校名称:{{ name }}</h2>
        <h2>学校地址:{{ address }}</h2>
    </div>
</template>

<script>
    //引入一个hunhe
    // import {hunhe,hunhe2} from '../mixin'
    export default {
        name: "School",
        data() {
            return {
                name: "尚硅谷",
                address: "北京",
                x: 666,
                // 如果混入与自身有同名属性。自身属性优先级高
            };
        },
        // mixins:[hunhe,hunhe2],
};
</script>

Student.vue

<template>
    <div>
        <h2 @click="showName">学生姓名:{{ name }}</h2>
        <h2>学生性别:{{ sex }}</h2>
    </div>
</template>

<script>
    //局部混合:
    // import {hunhe,hunhe2} from '../mixin'
    export default {
        name: "Student",
        data() {
            return {
                name: "张三",
                sex: "男",
            };
        },
        // mixins:[hunhe,hunhe2]
    };
</script>

App.vue

<template>
    <div>
        <School/>
        <hr>
        <Student/>
    </div>
</template>
<script>
    import School from './components/School'
    import Student from './components/Student'
    export default {
        name:'App',
        components:{School,Student}
    }
</script>

main.js

//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
// 全局混合,给所有的vm和vc得到混合
import { hunhe, hunhe2 } from './mixin'
Vue.mixin(hunhe)
Vue.mixin(hunhe2)

//创建vm
new Vue({
	el: '#app',
	render: h => h(App)
})

mixin.js 名字可以自己取

export const hunhe = {
    methods: {
        showName(){
            alert(this.name)
        }
    },
    mounted() {
        console.log('你好啊!')
    },
}
export const hunhe2 = {
    data() {
        return {
            x:100,
            y:200
        }
    },
}

插件

用于增强 Vue

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

对象.install = function (Vue, options) {
    // 1. 添加全局过滤器
    Vue.filter(....)

    // 2. 添加全局指令
    Vue.directive(....)

    // 3. 配置全局混入(合)
    Vue.mixin(....)

    // 4. 添加实例方法
    Vue.prototype.$myMethod = function () {...}
    Vue.prototype.$myProperty = xxxx
}

使用插件 Vue.use()

plugin.js

export default {
	install(Vue, x, y, z) {
		// 接收参数
		console.log(x, y, z)
		//全局过滤器,从第一位开始,找到前四个
		Vue.filter('mySlice', function (value) {
			return value.slice(0, 4)
		})
		//定义全局指令,自动获取焦点
		Vue.directive('fbind', {
			//指令与元素成功绑定时(一上来)
			bind(element, binding) {
				element.value = binding.value
			},
			//指令所在元素被插入页面时
			inserted(element, binding) {
				element.focus()
			},
			//指令所在的模板被重新解析时
			update(element, binding) {
				element.value = binding.value
			}
		})
		//定义混入
		Vue.mixin({
			data() {
				return {
					x: 100,
					y: 200
				}
			},
		})
		//给Vue原型上添加一个方法(vm和vc就都能用了)
		Vue.prototype.hello = () => { alert('你好啊') }
	}
}

main.js

//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//关闭Vue的生产提示
Vue.config.productionTip = false

//引入插件
import plugins from './plugins'
//应用(使用)插件
Vue.use(plugins, 1, 2, 3)
// 传入参数

//创建vm
new Vue({
	el: '#app',
	render: h => h(App)
})

scoped 样式

如果不同组件起了相同的样式名,会造成样式冲突,在 App.vue 中后 import 的组件样式会覆盖前面一个组件的同名样式,所以用 scoped 解决。最好不要在 App.vue 的 style 中加入 scoped,因为他是汇总组件,写在其中的样式为公共样式

  1. 作用: 让样式在局部生效,防止冲突

  2. 写法:

    <style lang="less" scoped> 
        //lang =''规定了用什么来写 style,不写默认为 css
        .demo{
            background-color: pink;
        }
    </style>
    

webStorage

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

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

  3. API

    1. ```xxxxxStorage.setItem('key', 'value');```
    该方法接受一个键和值作为参数,会把键值对添加到存储中,如果键名存在,则更新其对应的值。
    值为字符串,如果存入的值为对象,则将其转换为字符串后存入
    
    2. ```xxxxxStorage.getItem('person');```
    该方法接受一个键名作为参数,返回键名对应的值。对象转字符串后存入,取出后需将其重新转化为对象
    
    3. ```xxxxxStorage.removeItem('key');```
    该方法接受一个键名作为参数,并把该键名从存储中删除。
    
    4. ```xxxxxStorage.clear()```
    该方法会清空存储中的所有数据。
    

注:

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

localStorage.html

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8" />
        <title>localStorage</title>
    </head>

    <body>
        <h2>localStorage</h2>
        <button onclick="saveData()">点我保存一个数据</button>
        <button onclick="readData()">点我读取一个数据</button>
        <button onclick="deleteData()">点我删除一个数据</button>
        <button onclick="deleteAllData()">点我清空一个数据</button>

        <script type="text/javascript">
            let p = { name: '张三', age: 18 }

            function saveData() {
                localStorage.setItem('msg', 'hello!!!')
                localStorage.setItem('msg2', 666)
                localStorage.setItem('person', JSON.stringify(p))
            }

            function readData() {
                console.log(localStorage.getItem('msg'))
                console.log(localStorage.getItem('msg2'))
                const result = localStorage.getItem('person')
                JSON.parse(result)
                // console.log(localStorage.getItem('msg3'))
            }

            function deleteData() {
                localStorage.removeItem('msg2')
            }

            function deleteAllData() {
                localStorage.clear()
            }
        </script>
    </body>
</html>

sessionStorage.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>sessionStorage</title>
    </head>
    <body>
        <h2>sessionStorage</h2>
        <button onclick="saveData()">点我保存一个数据</button>
        <button onclick="readData()">点我读取一个数据</button>
        <button onclick="deleteData()">点我删除一个数据</button>
        <button onclick="deleteAllData()">点我清空一个数据</button>

        <script type="text/javascript" >
            let p = {name:'张三',age:18}

            function saveData(){
                sessionStorage.setItem('msg','hello!!!')
                sessionStorage.setItem('msg2',666)
                sessionStorage.setItem('person',JSON.stringify(p))
            }
            function readData(){
                console.log(sessionStorage.getItem('msg'))
                console.log(sessionStorage.getItem('msg2'))

                const result = sessionStorage.getItem('person')
                console.log(JSON.parse(result))

                // console.log(sessionStorage.getItem('msg3'))
            }
            function deleteData(){
                sessionStorage.removeItem('msg2')
            }
            function deleteAllData(){
                sessionStorage.clear()
            }
        </script>
    </body>
</html>

组件自定义事件

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

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

  3. 绑定自定义事件

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

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

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

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

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

  6. 组件上也可以绑定原生DOM事件,需要使用 native 修饰符, 否则会被当成自定义事件

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

App.vue

<template>
<div class="app">
    <h1>{{ msg }},学生姓名是:{{ studentName }}</h1>

    <!-- 通过父组件给子组件传递函数类型的props实现:子给父传递数据 -->
    <School :getSchoolName="getSchoolName" />

    <!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(方法一,使用@或v-on) -->
    <!-- <Student @atguigu="getStudentName" @demo="m1" /> -->
    <!-- 方法一:2.给student组件的实例对象vc绑定一个事件 -->

    <!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(方法二,使用ref) -->
    <Student ref="student" @click.native="show" />
    <!-- 方法二:2.给student绑定ref获取组件实例对象 -->
    </div>
</template>

<script>
    import Student from "./components/Student";
    import School from "./components/School";

    export default {
        name: "App",
        components: { School, Student },
        data() {
            return {
                msg: "你好啊!",
                studentName: "",
            };
        },
        methods: {
            getSchoolName(name) {
                console.log("App收到了学校名:", name);
            },
            getStudentName(name, ...params) {
                //方法一/二:1.定义一个方法
                console.log("App收到了学生名:", name, params);
                //   接收name和一个数组对象,数组内存储着其余参数
                this.studentName = name;
            },
            m1() {
                console.log("demo事件被触发了!");
            },
            show() {
                alert(123);
            },
        },
        mounted() {
            // 方法二:3.App.vue挂载完毕,获取student的组件实例对象,绑定自定义事件
            this.$refs.student.$on("atguigu", this.getStudentName); //绑定自定义事件
            // this.$refs.student.$once('atguigu',this.getStudentName) //绑定自定义事件(一次性)
        },
    };
</script>

<style scoped>
    .app {
        background-color: gray;
        padding: 5px;
    }
</style>

student.vue

<template>
<div class="student">
    <h2>学生姓名:{{ name }}</h2>
    <h2>学生性别:{{ sex }}</h2>
    <h2>当前求和为:{{ number }}</h2>
    <button @click="add">点我number++</button>、
    <!-- 方法一:3.定义 sendStudentlName点击事件-->
    <button @click="sendStudentlName">把学生名给App</button>
    <button @click="unbind">解绑atguigu事件</button>
    <button @click="death">销毁当前Student组件的实例(vc)</button>
    </div>
</template>

<script>
    export default {
        name: "Student",
        data() {
            return {
                name: "张三",
                sex: "男",
                number: 0,
            };
        },
        methods: {
            add() {
                console.log("add回调被调用了");
                this.number++;
            },
            sendStudentlName() {
                //方法一/二:4.触发Student组件实例身上的atguigu事件
                this.$emit("atguigu", this.name, 666, 888, 900);
                // this.$emit("demo");
                // 触发Student组件实例身上的demo事件
                // this.$emit('click')
            },
            unbind() {
                this.$off("atguigu"); //解绑一个自定义事件
                // this.$off(['atguigu','demo']) //解绑多个自定义事件
                // this.$off() //解绑所有的自定义事件
            },
            death() {
                this.$destroy();
                //销毁了当前Student组件的实例,销毁后所有Student实例的自定义事件全都不奏效,
                // 原生DOM事件不受影响,但页面响应式丢了。
            },
        },
    };
</script>

<style scoped>
    .student {
        background-color: pink;
        padding: 5px;
        margin-top: 30px;
    }
</style>

school.vue

<template>
<div class="school">
    <h2>学校名称:{{name}}</h2>
    <h2>学校地址:{{address}}</h2>
    <button @click="sendSchoolName">把学校名给App</button>
    </div>
</template>

<script>
    export default {
        name:'School',
        props:['getSchoolName'],
        data() {
            return {
                name:'尚硅谷',
                address:'北京',
            }
        },
        methods: {
            sendSchoolName(){
                this.getSchoolName(this.name)
            }
        },
    }
</script>

<style scoped>
    .school{
        background-color: skyblue;
        padding: 5px;
    }
</style>

全局事件总线

1.Vue原型对象上包含事件处理的方法
    1)$on(eventName,listener):绑定自定义事件监听
    2)$emit(eventName,data):分发自定义事件
    3)$off(eventName):解绑自定义事件监听
    4)$once(eventName,listener):绑定事件监听,但只能处理一次
2.所有组件实例对象的原型对象的原型对象就是Vue的原型对象
    1)所有组件对象都能看到Vue原型对象上的属性和方法
    2)Vue.prototype.$bus=new Vue(),所有的组件对象都能看到$bus这个属性对象
3.全局事件总线
    1)包含事件处理相关方法的对象(只有一个)
    2)所有的组件都可以得到
  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)
        //回调methods提供的demo方法或直接使用箭头函数
      }
      
    2. 提供数据:

      //在提供数据的组件的methods中书写
      this.$bus.$emit('xxxx',数据)
      
  4. 最好在 beforeDestroy 钩子中,用 $off 去解绑当前组件所用到的事件

main.js

//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'
//关闭Vue的生产提示
Vue.config.productionTip = false

//创建vm
new Vue({
    el:'#app',
    render: h => h(App),
    beforeCreate() {
        Vue.prototype.$bus = this //安装全局事件总线
    },
})

App.vue

<template>
<div class="app">
    <h1>{{msg}}</h1>
    <School/>
    <Student/>
    </div>
</template>

<script>
    import Student from './components/Student'
    import School from './components/School'

    export default {
        name:'App',
        components:{School,Student},
        data() {
            return {
                msg:'你好啊!',
            }
        }
    }
</script>

<style scoped>
    .app{
        background-color: gray;
        padding: 5px;
    }
</style>

Student.vue

<template>
<div class="student">
    <h2>学生姓名:{{ name }}</h2>
    <h2>学生性别:{{ sex }}</h2>
    <button @click="sendStudentName">把学生名给School组件</button>
    </div>
</template>

<script>
    export default {
        name: "Student",
        data() {
            return {
                name: "张三",
                sex: "男",
            };
        },
        mounted() {
            // console.log('Student',this.x)
        },
        methods: {
            sendStudentName() {
                this.$bus.$emit("hello", this.name);
                //提供数据,将student组件中的数据传递给school
            },
        },
    };
</script>

<style  scoped>
    .student {
        background-color: pink;
        padding: 5px;
        margin-top: 30px;
    }
</style>

School.vue

<template>
<div class="school">
    <h2>学校名称:{{ name }}</h2>
    <h2>学校地址:{{ address }}</h2>
    </div>
</template>

<script>
    export default {
        name: "School",
        data() {
            return {
                name: "尚硅谷",
                address: "北京",
            };
        },
        mounted() {
            // console.log('School',this)
            this.$bus.$on("hello", (data) => {
                console.log("我是School组件,收到了数据", data);
            });
        },
        beforeDestroy() {
            this.$bus.$off("hello");
            // 最好在beforeDestroy钩子中,用$off去解绑当前组件所用到的事件,一定要写解绑的事件名,否则就全部解绑了
        },
    };
</script>

<style scoped>
    .school {
        background-color: skyblue;
        padding: 5px;
    }
</style>

Vue 过渡与动画

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

  1. v-enter : 定义进入过渡的开始状态。在元素被插入之前生效,在元素被插入之后的下一帧移除
  2. v-enter-active : 定义进入过渡生效时的状态。在整个进入过渡的阶段中应用,在元素被插入之前生效,在过渡/动画完成之后移除。这个类可以被用来定义进入过渡的过程时间,延迟和曲线函数
  3. v-enter-to : 2.1.8 版及以上定义进入过渡的结束状态。在元素被插入之后下一帧生效(与此同时v-enter被移除),在过渡/动画完成之后移除
  4. v-leave : 定义离开过渡的开始状态。在离开过渡被触发时立刻生效,下一帧被移除
  5. v-leave-active : 定义离开过渡生效时的状态。在整个离开过渡的阶段中应用,在离开过渡被触发时立刻生效,在过渡/动画完成之后移除。这个类可以被用来定义离开过渡的过程时间,延迟和曲线函数
  6. v-leave-to : 2.1.8 版及以上定义离开过渡的结束状态。在离开过渡被触发之后下一帧生效(与此同时 v-leave 被删除),在过渡/动画完成之后移除

写法

准备好样式:

  • 元素进入的样式:
    1. v-enter:进入的起点
    2. v-enter-active:进入过程中
    3. v-enter-to:进入的终点
  • 元素离开的样式:
    1. v-leave:离开的起点
    2. v-leave-active:离开过程中
    3. v-leave-to:离开的终点

写法:

使用 <transition> 包裹要过渡的元素, 并配置name属性:

<transition name="hello" appear>
	<h1 v-show="isShow">你好啊!</h1>
</transition>

appear 是页面第一次刷新时出现的样式

若有多个元素需要过渡, 需要使用 <transition-group>, 每个元素都要指定 key 值

用动画实现

<template>
    <div>
        <button @click="isShow = !isShow">显示/隐藏</button>
        <transition name="hello" appear>
            <h1 v-show="isShow">你好啊!</h1>
        </transition>
    </div>
</template>

<script>
    export default {
        name: "Test",
        data() {
            return {
                isShow: true,
            };
        },
    };
</script>

<style scoped>
    h1 {
        background-color: orange;
    }
    /* 用动画实现 */
    .hello-enter-active {
        animation: atguigu 0.5s linear;
    }
    /* transition添加name属性之后
    默认的v-enter-active改为name-enter-active
    */
    .hello-leave-active {
        animation: atguigu 0.5s linear reverse;
    }

    @keyframes atguigu {
        from {
            transform: translateX(-100%);
        }
        to {
            transform: translateX(0px);
        }
    }
</style>

用过渡实现

<template>
    <div>
        <button @click="isShow = !isShow">显示/隐藏</button>
        <transition-group name="hello" appear>
            <h1 v-show="!isShow" key="1">你好啊!</h1>
            <h1 v-show="isShow" key="2">尚硅谷!</h1>
        </transition-group>
        <!-- 多个元素过渡 -->
    </div>
</template>

<script>
    export default {
        name: "Test",
        data() {
            return {
                isShow: true,
            };
        },
    };
</script>

<style scoped>
    h1 {
        background-color: orange;
    }
    /* 用过度实现 */
    /* 进入的起点、离开的终点 */
    .hello-enter,
    .hello-leave-to {
        transform: translateX(-100%);
    }

    /* 过渡过程 */
    .hello-enter-active,
    .hello-leave-active {
        transition: 0.5s linear;
    }

    /* 进入的终点、离开的起点 */
    .hello-enter-to,
    .hello-leave {
        transform: translateX(0);
    }
</style>

第三方库实现

Animate.css

<template>
    <div>
        <button @click="isShow = !isShow">显示/隐藏</button>
        <!--在name中加入 animate__animated animate__bounce-->
        <transition-group
                          appear
                          name="animate__animated animate__bounce"
                          enter-active-class="animate__backInUp"
                          leave-active-class="animate__backOutUp"
                          >
            <h1 v-show="!isShow" key="1">你好啊!</h1>
            <h1 v-show="isShow" key="2">尚硅谷!</h1>
        </transition-group>
    </div>
</template>

<script>
    import "animate.css";
    export default {
        name: "Test",
        data() {
            return {
                isShow: true,
            };
        },
    };
</script>

<style scoped>
    h1 {
        background-color: orange;
    }
</style>

Vue ajax

在脚手架的控制台安装 axios: npm i axios

通过 vue-cli 配置代理服务器来解决跨域问题

方法一

在 vue.config.js 中添加如下配置:

devServer:{
  proxy:"http://localhost:5000"
  //配置代理服务器,这个路径端口号要与传送数据的服务器端口号一致
}

说明:

  1. 优点:配置简单,请求资源时直接发给前端(8080)即可
  2. 缺点:不能配置多个代理。不能灵活的控制请求是否走代理,这会告诉开发服务器将任何未知请求 (没有匹配到静态文件的请求) 代理到http://localhost:5000
  3. 工作方式:若按照上述配置代理,当请求了前端不存在的资源时,那么该请求会转发给服务器 ,若自身带有同名资源,则优先使用自身资源(优先匹配前端资源

方法二

编写 vue.config.js 配置具体代理规则:

module.exports = {
    devServer: {
        proxy: {
            '/api1': {// 匹配所有以 '/api1'开头的请求路径
                target: 'http://localhost:5000',// 代理目标的基础路径,路径到5000就不往后写了
                changeOrigin: true,
                pathRewrite: {'^/api1': ''} //重写路径
            },
            '/api2': {// 匹配所有以 '/api2'开头的请求路径
                target: 'http://localhost:5001',// 代理目标的基础路径
                changeOrigin: true,
                pathRewrite: {'^/api2': ''} //重写路径
            }
        }
    }
}
/*
       changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:5000
       changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:8080
       changeOrigin默认值为true
    */
  1. 优点:可以配置多个代理,且可以灵活的控制请求是否走代理
  2. 缺点:配置略微繁琐,请求资源时必须加前缀

插槽

父组件向子组件传递带数据的标签, 当一个组件有不确定的结构时,就需要使用 slot 技术, 注意: 插槽内容是在父组件中编译后, 再传递给子组件的

让父组件可以向子组件指定位置插入 html 结构,也是一种组件间通信的方式,适用于 父组件 ===> 子组件

分类: 默认插槽、具名插槽、作用域插槽

默认插槽

父组件中:
<Category>
    <div>html结构1</div>
</Category>

子组件中:
<template>
    <div>
        <!-- 定义插槽 -->
        <slot>插槽默认内容...</slot>
    </div>
</template>

具名插槽

父组件中:
<Category>
    <div slot="center">
        <!-- 放入指定名字的插槽中-->
        <div>html结构1</div>
    </div>
    <!-- 两种写法,但 v-slot:footer只能用在template标签中-->
    <template v-slot:footer>
        <div>html结构2</div>
    </template>
</Category>

子组件中:
<template>
    <div>
        <!-- 定义插槽 -->
        <slot name="center">插槽默认内容...</slot>
        <slot name="footer">插槽默认内容...</slot>
    </div>
</template>

作用域插槽

数据在组件的自身(在 slot 插槽定义的那个组件里面),但根据数据生成的结构需要组件的使用者来决定.(games 数据在 Category 组件中,但使用数据所遍历出来的结构由 App 组件决定)

注: 作用域插槽也可以取名字

父组件中:
<Category>
    //必须包裹template标签,scope属性标签必带,收到数据,但" "内名字随意起
    <template scope="scopeData">
        1<!-- 生成的是ul列表 -->
        <ul>
            <li v-for="g in scopeData.games" :key="g">{{g}}</li>
        </ul>
    </template>
</Category>

<Category>
    <template slot-scope="scopeData">
        <!-- 生成的是h4标题 -->
        <h4 v-for="g in scopeData.games" :key="g">{{g}}</h4>
    </template>
</Category>

子组件中:
<template>
    <div>
        // 通过插槽将数据从子组件传递给父组件
        <slot :games="games"></slot>
    </div>
</template>
<script>
    export default {
        name:'Category',
        props:['title'],
        // 数据在子组件自身
        data() {
            return {
                games:['红色警戒','穿越火线','劲舞团','超级玛丽']
            }
        },
    }
</script>

不使用插槽

Category

<template>
    <div class="category">
        <h3>{{ title }}分类</h3>
        <ul>
            <li v-for="(item, index) in listData" :key="index">{{ item }}</li>
        </ul>
    </div>
</template>

<script>
    export default {
        name: "Category",
        props: ["title", "listData"],
    };
</script>

<style scoped>
    .category {
        background-color: skyblue;
        width: 200px;
        height: 300px;
    }
    h3 {
        text-align: center;
        background-color: orange;
    }
    video {
        width: 100%;
    }
    img {
        width: 100%;
    }
</style>

App.vue

<template>
    <div class="container">
        <Category title="美食" :listData="foods"></Category>
        <Category title="游戏" :listData="games"></Category>
        <Category title="电影" :listData="films"></Category>
    </div>
</template>

<script>
    import Category from "./components/Category";
    export default {
        name: "App",
        components: { Category },
        data() {
            return {
                foods: ["火锅", "烧烤", "小龙虾", "牛排"],
                games: ["红色警戒", "穿越火线", "劲舞团", "超级玛丽"],
                films: ["《教父》", "《拆弹专家》", "《你好,李焕英》", "《与神同行》"],
            };
        },
    };
</script>

<style scoped>
    .container {
        display: flex;
        justify-content: space-around;
    }
</style>

默认插槽

App.vue

<template>
    <div class="container">
        <Category title="美食" >
            <img src="https://s3.ax1x.com/2021/01/16/srJlq0.jpg" alt="">
        </Category>

        <Category title="游戏" >
            <ul>
                <li v-for="(g,index) in games" :key="index">{{g}}</li>
            </ul>
        </Category>

        <Category title="电影">
            <video controls src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"></video>
        </Category>
    </div>
</template>

<script>
    import Category from './components/Category'
    export default {
        name:'App',
        components:{Category},
        data() {
            return {
                foods:['火锅','烧烤','小龙虾','牛排'],
                games:['红色警戒','穿越火线','劲舞团','超级玛丽'],
                films:['《教父》','《拆弹专家》','《你好,李焕英》','《与神同行》']
            }
        },
    }
</script>

<style scoped>
    .container{
        display: flex;
        justify-content: space-around;
    }
</style>

Category

<template>
    <div class="category">
        <h3>{{title}}分类</h3>
        <!-- 定义一个插槽(挖个坑,等着组件的使用者进行填充) -->
        <slot>我是一些默认值,当使用者没有传递具体结构时,我会出现</slot>
    </div>
</template>

<script>
    export default {
        name:'Category',
        props:['title']
    }
</script>

<style scoped>
    .category{
        background-color: skyblue;
        width: 200px;
        height: 300px;
    }
    h3{
        text-align: center;
        background-color: orange;
    }
    video{
        width: 100%;
    }
    img{
        width: 100%;
    }
</style>

具名插槽

Category

<template>
    <div class="category">
        <h3>{{title}}分类</h3>
        <!-- 定义一个插槽(挖个坑,等着组件的使用者进行填充) -->
        <slot name="center">定义一个名为center的插槽</slot>
        <slot name="footer">定义一个名为footer的插槽</slot>
    </div>
</template>

<script>
    export default {
        name:'Category',
        props:['title']
    }
</script>

<style scoped>
    .category{
        background-color: skyblue;
        width: 200px;
        height: 300px;
    }
    h3{
        text-align: center;
        background-color: orange;
    }
    video{
        width: 100%;
    }
    img{
        width: 100%;
    }
</style>

App.vue

<template>
    <div class="container">
        <Category title="美食">
            //放入center插槽中
            <img
                 slot="center"
                 src="https://s3.ax1x.com/2021/01/16/srJlq0.jpg"
                 alt=""
                 />
            //放入footer插槽中
            <a slot="footer" href="http://www.atguigu.com">更多美食</a>
        </Category>

        <Category title="游戏">
            <ul slot="center">
                <li v-for="(g, index) in games" :key="index">{{ g }}</li>
            </ul>
            <div class="foot" slot="footer">
                <a href="http://www.atguigu.com">单机游戏</a>
                <a href="http://www.atguigu.com">网络游戏</a>
            </div>
        </Category>

        <Category title="电影">
            <video
                   slot="center"
                   controls
                   src="http://clips.vorwaerts-gmbh.de/big_buck_bunny.mp4"
                   ></video>
            <template v-slot:footer>
                <!-- 两种写法,但 v-slot:footer只能用在template标签中-->
                <div class="foot">
                    <a href="http://www.atguigu.com">经典</a>
                    <a href="http://www.atguigu.com">热门</a>
                    <a href="http://www.atguigu.com">推荐</a>
                </div>
                <h4>欢迎前来观影</h4>
            </template>
        </Category>
    </div>
</template>

<script>
    import Category from "./components/Category";
    export default {
        name: "App",
        components: { Category },
        data() {
            return {
                foods: ["火锅", "烧烤", "小龙虾", "牛排"],
                games: ["红色警戒", "穿越火线", "劲舞团", "超级玛丽"],
                films: ["《教父》", "《拆弹专家》", "《你好,李焕英》", "《与神同行》"],
            };
        },
    };
</script>
<style scoped>
    .container,
    .foot {
        display: flex;
        justify-content: space-around;
    }
    h4 {
        text-align: center;
    }
</style>

作用域插槽

App.vue

<template>
    <div class="container">
        <Category title="游戏">
            <!-- 必须包裹template标签,scope属性标签必带,收到数据,但" "内名字随意起 -->
            <template scope="atguigu">
                <ul>
                    <li v-for="(g, index) in atguigu.games" :key="index">{{ g }}</li>
                </ul>
            </template>
        </Category>

        <Category title="游戏">
            <template scope="{ games }">
                <!-- 解构赋值 -->
                <ol>
                    <li style="color: red" v-for="(g, index) in games" :key="index">
                        {{ g }}
                    </li>
                </ol>
            </template>
        </Category>

        <Category title="游戏">
            <template slot-scope="atguigu">
                <!--slot-scope是新的API,作用与scope一样 -->
                <h4 v-for="(g, index) in atguigu.games" :key="index">{{ g }}</h4>
            </template>
        </Category>
    </div>
</template>

<script>
    import Category from "./components/Category";
    export default {
        name: "App",
        components: { Category },
    };
</script>

<style scoped>
    .container,
    .foot {
        display: flex;
        justify-content: space-around;
    }
    h4 {
        text-align: center;
    }
</style>

Category

<template>
    <div class="category">
        <h3>{{title}}分类</h3>
        <slot :games="games" msg="hello">我是默认的一些内容</slot>
    </div>
</template>

<script>
    export default {
        name:'Category',
        props:['title'],
        data() {
            return {
                games:['红色警戒','穿越火线','劲舞团','超级玛丽'],
            }
        },
    }
</script>

<style scoped>
    .category{
        background-color: skyblue;
        width: 200px;
        height: 300px;
    }
    h3{
        text-align: center;
        background-color: orange;
    }
    video{
        width: 100%;
    }
    img{
        width: 100%;
    }
</style>

Vuex

在 Vue 中实现 集中式状态(数据) 管理的一个 Vue 插件,对 vue 应用中多个组件的共享状态进行集中式的管理 (读/写), 也是一种组件间通信的方式,且适用于任意组件间通信

什么时候使用?

  1. 多个组件依赖于同一状态(数据)
  2. 来自不同组件的行为需要变更同一状态(数据)
  3. 即多个组件需要共享数据时

将很多组件都要使用的数据存储在 vuex 中,通过 API 的调用实现读写

Vuex 工作原理


搭建 vuex 环境

安装: npm i vuex
  1. 创建文件: src/store/index.js

    //引入Vue核心库
    import Vue from 'vue'
    //引入Vuex
    import Vuex from 'vuex'
    //应用Vuex插件
    Vue.use(Vuex)
    
    //准备actions对象——响应组件中用户的动作
    const actions = {}
    //准备mutations对象——修改state中的数据
    const mutations = {}
    //准备state对象——保存具体的数据
    const state = {}
    
    //创建并暴露store
    export default new Vuex.Store({
        actions,
        mutations,
        state
    })
    
  2. main.js 中创建 vm 时传入 store 配置项

    ......
    //引入store
    import store from './store/index'
    ......
    
    //创建vm
    new Vue({
    	el:'#app',
    	render: h => h(App),
    	store
    })
    

基本使用

  1. 初始化数据、配置 actions、配置 mutations,操作文件 store.js

    //引入Vue核心库
    import Vue from 'vue'
    //引入Vuex
    import Vuex from 'vuex'
    //引用Vuex
    Vue.use(Vuex)
    
    const actions = {
        //响应组件中加的动作
    	jia(context,value){
    		// console.log('actions中的jia被调用了',miniStore,value)
    		context.commit('JIA',value)
    	},
    }
    
    const mutations = {
        //执行加
    	JIA(state,value){
    		// console.log('mutations中的JIA被调用了',state,value)
    		state.sum += value
    	}
    }
    
    //初始化数据
    const state = {
       sum:0
    }
    
    //创建并暴露store
    export default new Vuex.Store({
    	actions,
    	mutations,
    	state,
    })
    
  2. 组件中读取vuex中的数据:$store.state.sum

  3. 组件中修改vuex中的数据:$store.dispatch('action中的方法名',数据)$store.commit('mutations中的方法名',数据)

注: 若逻辑不复杂(如没有网络请求或其他业务逻辑, 组件也可以越过 actions, 直接写 commit)

getters 的使用

当 state 中的数据需要经过加工后再使用时,可以使用 getters 加工

store.js 中追加 getters配置

......
const getters = {
	bigSum(state){
		return state.sum * 10
	}
}

//创建并暴露store
export default new Vuex.Store({
	......
	getters
})

组件中读取数据: $.store.getters.bigSum

四个 map 方法的使用

首先 import {mapState,mapGetters,mapMutations,mapActions} from 'vuex'

  • mapState: 用于帮助我们映射 state 中的数据为计算属性

    computed: {
        //借助mapState生成计算属性:sum、school、subject(对象写法)
         ...mapState({sum:'sum',school:'school',subject:'subject'}),
             
        //借助mapState生成计算属性:sum、school、subject(数组写法)
        ...mapState(['sum','school','subject']),
    },
    
  • mapGetters: 用于映射 getters 中的数据为计算属性

    computed: {
        //借助mapGetters生成计算属性:bigSum(对象写法)
        ...mapGetters({bigSum:'bigSum'}),
    
        //借助mapGetters生成计算属性:bigSum(数组写法)
        ...mapGetters(['bigSum'])
    },
    
  • mapAction: 用于生成与 actions 对话的方法,即:包含$store.dispatch(xxx)的函数

    methods:{
         //使用这个方法需要在点击函数中传参----看案例
        //靠mapActions生成:increment、decrement(对象形式)
        ...mapMutations({increment:'JIA',decrement:'JIAN'}),
        
        //靠mapMutations生成:JIA、JIAN(对象形式)
        ...mapMutations(['JIA','JIAN']),
    }
    

    备注:mapActions与mapMutations使用时,若需要传递参数需要:在模板中绑定事件时传递好参数,否则参数是事件对象

模块化+命名空间

让代码更好维护, 让多种数据分类更加明确

  1. 修改 store.js

    const countAbout = {
      namespaced:true,//开启命名空间,必需
      state:{x:1},
      mutations: { ... },
      actions: { ... },
      getters: {
        bigSum(state){
           return state.sum * 10
        }
      }
    }
    
    const personAbout = {
      namespaced:true,//开启命名空间,必需
      state:{ ... },
      mutations: { ... },
      actions: { ... }
    }
    
    export default new Vuex.Store({
     modules: {
     	countAbout: countOptions,
     	personAbout: personOption
     }
    })
    
  2. 组件读取 state 数据

    //方式一:自己直接读取
    this.$store.state.personAbout.list
    //方式二:借助mapState读取:
    ...mapState('countAbout',['sum','school','subject']),
    
  3. 组件读取 getters 数据

    //方式一:自己直接读取
    this.$store.getters['personAbout/firstPersonName']
    //方式二:借助mapGetters读取:
    ...mapGetters('countAbout',['bigSum'])
    
  4. 组件调用 dispatch

    //方式一:自己直接dispatch
    this.$store.dispatch('personAbout/addPersonWang',person)
    //方式二:借助mapActions:
    ...mapActions('countAbout',{incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
    
  5. 组件调用 commit

    //方式一:自己直接commit
    this.$store.commit('personAbout/ADD_PERSON',person)
    //方式二:借助mapMutations:
    ...mapMutations('countAbout',{increment:'JIA',decrement:'JIAN'}),
    

求和案例

Count.vue

<template>
    <div>
        <h1>当前求和为:{{ sum }}</h1>
        <h3>当前求和放大10倍为:{{ bigSum }}</h3>
        <h3>我在{{ school }},学习{{ subject }}</h3>
        <h3 style="color: red">Person组件的总人数是:{{ personList.length }}</h3>
        <select v-model.number="n">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
        </select>
        <button @click="increment(n)">+</button>
        <button @click="decrement(n)">-</button>
        <button @click="incrementOdd(n)">当前求和为奇数再加</button>
        <button @click="incrementWait(n)">等一等再加</button>
    </div>
</template>

<script>
    import { mapState, mapGetters, mapMutations, mapActions } from "vuex";
    export default {
        name: "Count",
        data() {
            return {
                n: 1, //用户选择的数字
            };
        },
        computed: {
            //借助mapState生成计算属性,从state中读取数据。(数组写法)
            ...mapState("countAbout", ["sum", "school", "subject"]),
            ...mapState("personAbout", ["personList"]),
            //借助mapGetters生成计算属性,从getters中读取数据。(数组写法)
            ...mapGetters("countAbout", ["bigSum"]),
        },
        methods: {
            //借助mapMutations生成对应的方法,方法中会调用commit去联系mutations(对象写法)
            ...mapMutations("countAbout", { increment: "JIA", decrement: "JIAN" }),
            //借助mapActions生成对应的方法,方法中会调用dispatch去联系actions(对象写法)
            ...mapActions("countAbout", {
                incrementOdd: "jiaOdd",
                incrementWait: "jiaWait",
            }),
        },
        mounted() {
            // console.log(this.$store);
        },
    };
</script>

<style lang="css">
    button {
        margin-left: 5px;
    }
</style>

count.js

// 求和相关配置
const countOptions = {
    namespaced: true,
    // 添加命名空间
    actions: {
        jiaOdd(context, value) {
            if (context.state.sum % 2) {
                context.commit('JIA', value)
            }
        },
        jiaWait(context, value) {
            setTimeout(() => {
                context.commit('JIA', value)
            }, 500)
        }
    },
    mutations: {
        JIA(state, value) {
            state.sum += value
        },
        JIAN(state, value) {
            state.sum -= value
        },
    },
    state: {
        sum: 0,
        school: '尚硅谷',
        subject: '前端',
    },
    getters: {
        bigSum(state) {
            return state.sum * 10
        }
    },
}
export default countOptions

Person.vue

<template>
  <div>
    <h1>人员列表</h1>
    <h3 style="color: red">Count组件求和为:{{ sum }}</h3>
    <h3 style="color: red">列表中第一个人的名字是:{{ firstPersonName }}</h3>
    <input type="text" placeholder="请输入名字" v-model="name" />
    <button @click="add">添加</button>
    <button @click="addWang">添加一个姓王的人</button>
    <button @click="addServer">随机添加一个名字奇怪的人</button>
    <ul>
      <li v-for="p in personList" :key="p.id">{{ p.name }}</li>
    </ul>
  </div>
</template>

<script>
import { nanoid } from "nanoid";
export default {
  name: "Person",
  data() {
    return {
      name: "",
    };
  },
  computed: {
    personList() {
      // 这里和之前相比代码改变了
      return this.$store.state.personAbout.personList;
    },
    sum() {
      return this.$store.state.countAbout.sum;
    },
    firstPersonName() {
      return this.$store.getters["personAbout/firstPersonName"];
    },
  },
  methods: {
    add() {
      const personObj = { id: nanoid(), name: this.name };
      // 这里和之前相比代码改变了
      this.$store.commit("personAbout/ADD_PERSON", personObj);
      //   this.$store.commit("分类名/ADD_PERSON", personObj);
      this.name = "";
    },
    addWang() {
      const personObj = { id: nanoid(), name: this.name };
      this.$store.dispatch("personAbout/addPersonWang", personObj);
      this.name = "";
    },
    addServer() {
      this.$store.dispatch("personAbout/addPersonServer");
    },
  },
};
</script>

person.js

import axios from 'axios'
import { nanoid } from 'nanoid'
// 人员管理相关配置
const personOption = {
    namespaced: true,
    // 添加命名空间
    actions: {
        addPersonWang(context, value) {
            if (value.name.indexOf('王') === 0) {
                context.commit('ADD_PERSON', value)
            } else {
                alert("添加的人必须姓王")
            }
        },
        addPersonServer(context) {
            axios.get('https://api.uixsj.cn/hitokoto/get?type=social').then(
                response => {
                    context.commit('ADD_PERSON', { id: nanoid(), name: response.data })
                },
                error => {
                    alert(error.message)
                }
            )
        }
    },
    mutations: {
        ADD_PERSON(state, value) {
            state.personList.unshift(value)
        }
    },
    state: {
        personList: [
            { id: '001', name: '张三' }
        ]
    },
    getters: {
        firstPersonName(state) {
            return state.personList[0].name
        }
    },
}
export default personOption

App.vue

<template>
    <div>
        <Count />
        <hr />
        <Person />
    </div>
</template>

<script>
    import Count from "./components/Count";
    import Person from "./components/Person";

    export default {
        name: "App",
        components: { Count, Person },
        mounted() {
            // console.log('App',this)
        },
    };
</script>

index.js

该文件用于创建 Vuex 中最为核心的 store

import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
//应用Vuex插件
Vue.use(Vuex)

import countOptions from './count'
import personOption from './person'
//创建并暴露store
export default new Vuex.Store({
	modules: {
		countAbout: countOptions,
		personAbout: personOption
	}
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值