二,Vue组件化编程
2.1模块与组件、模块化与组件化
2.1.1.模块
- 理解:向外提供特定功能的js程序,一般就是一个js文件
- 为什么:js文件很多很复杂
- 作用:复用js,简化js的编写,提高js运行效率
2.1.2.组件
- 理解:用来实现局部(特定)功能效果的代码集合(html/css/js/image……)
- 为什么:一个界面的功能很复杂
- 作用:复用编码,简化项目编码,提高运行效率
2.1.3.模块化
当应用中的js都以模块来编写的,那这个应用就是一个模块化的应用。
2.1.4.组件化
当应用中的功能都是多组件的方式来编写的,那这个应用就是一个组件化的应用。
2.2.非单文件组件
- 模板编写没有提示
- 没有构建过程,无法将ES6转换成ES5
- 不支持组件的CSS
- 真正开发中几乎不用
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> <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">
Vue.config.productionTip = false
//第一步:创建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>
复制代码
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
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>几个注意点</title>
<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
//定义组件
const s = {
name: 'atguigu',
template: `
<div>
<h2>学校名称:{{name}}</h2>
<h2>学校地址:{{address}}</h2>
</div>
`,
data() {
return {
name: '尚硅谷',
address: '北京'
}
}
}
new Vue({
el: '#root',
components: {
"school": s
}
})
</script>
</html>
2.2.3组件的嵌套
子组件要在父组件之前定义
<!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>
复制代码
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。vm管理着vc
如图所示:打印出vm,展开,$children中包含着两个vc
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>VueComponent</title>
<script type="text/javascript" src="../js/vue.js"></script>
</head>
<body>
<!-- 准备好一个容器-->
<div id="root">
<school></school>
<hello></hello>
</div>
</body>
<script type="text/javascript">
Vue.config.productionTip = false
//定义school组件
const school = Vue.extend({
name: 'school',
template: `
<div>
<h2>学校名称:{{name}}</h2>
<h2>学校地址:{{address}}</h2>
<button @click="showName()">点我提示学校名</button>
</div>
`,
data() {
return {
name: '尚硅谷',
address: '北京'
}
},
methods: {
showName() {
console.log('showName:', this)
}
},
})
const test = Vue.extend({
template: `<span>atguigu</span>`
})
//定义hello组件
const hello = Vue.extend({
template: `
<div>
<h2>{{msg}}</h2>
<test></test>
</div>
`,
data() {
return {
msg: '你好啊!'
}
},
components: { test }
})
// console.log('@',school)
// console.log('#',hello)
//创建vm
const vm = new Vue({
el: '#root',
components: { school, hello }
})
console.log(vm);
</script>
</html>
复制代码
2.2.5 一个重要的内置关系
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>
复制代码
2.3单文件组件
大体结构是这样的:
**
2.3.1其余文件(这些文件内创建组件)
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>
复制代码
2.3.2 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>
<style>
</style>
2.3.3 main.js文件
import App from './App.vue'
// 在main.js文件中创建vue实例vm,并引入最高级的App.vue文件
new Vue({
el: '#root',
template: `<App></App>`,
components: { App },
})
复制代码
2.3.4 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脚手架
3.1初始化脚手架
3.1.1说明
1.Vue脚手架是Vue官方提供的标准化开发工具(开发平台).
2.最新的版本是4.x.
3.文档
3.1.2具体步骤
第一步(仅第一次执行):全局安装@vue/cli。
npm install -g @vue/cli
# OR
yarn global add @vue/cli
第二步:切换到你要创建项目的目录,然后使用命令创建项目
vue create xxxx
- vue2
- vue3
- 自定义
babel :ES6 ===>ES5
eslint:语法检查 第三步:启动项目
npm run serve
OR
yarn serve
关闭项目:
你还可以用这个命令来检查其版本是否正确:
vue --version
备注:
1.如出现下载缓慢请配置npm淘宝镜像:
npm config set registry https://registry.npm.taobao.org
2.Vue脚手架隐藏了所有webpack相关的配置,若想查看具体的webpakc配置,请执行:
vue inspect > output.js
3.2 分析脚手架
3.2.1 脚手架文件结构
├── 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.2.2 关于不同版本的Vue
- vue.js与vue.runtime.xxx.js的区别:
- vue.js是完整版的Vue,包含:核心功能 + 模板解析器。
- 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 函数
3.2.3 vue.config.js配置文件
- 使用vue inspect > output.js可以查看到Vue脚手架的默认配置,但无法更改。文件标红最外面加上const a ={},在output.js文件中
- 在根目录建立vue.config.js文件可以对脚手架进行个性化定制,详情见:
3.2.4 使用脚手架构建出来的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>
复制代码
3.2.5 使用脚手架构建出来的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 },
})
3.3 ref属性
- 被用来给元素或子组件注册引用信息(id的替代者)
- 应用在html标签上获取的是真实DOM元素,应用在组件标签上是组件实例对象(vc)
- 使用方式:
- 打标识:
.....
或 `` - 获取:
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>
复制代码
3.4 props配置项
-
功能:让组件接收外部传过来的数据
-
传递数据:``
-
接收数据:
-
第一种方式(只接收):
props:['name']
-
第二种方式(限制类型):
props:{name:String}
-
第三种方式(限制类型、限制必要性、指定默认值):
props:{ name:{ type:String, //类型 required:true, //必要性 default:'老王' //默认值 } }
-
备注:props是只读的,Vue底层会监测你对props的修改,如果进行了修改,就会发出警告,若业务需求确实需要修改,那么请复制props的内容到data中一份,然后去修改data中的数据。
props中接收的数据会被绑定到组件实例对象vc上,且优先级高于data中的数据,data中的数据属性名字不能与接收的props属性名一致
App.vue:
<template>
<div>
<Student name="李四" sex="女" :age="18" />
<!-- 在组件标签中声明传入属性
:即v-bind 将字符串18变为js表达式,使其可以接受加法运算
-->
</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>
复制代码
程序运行截图:页面中学生年龄点击增加,控制台中data中的属性myAge改变,props中age属性不变
3.5mixin(混入)
-
功能:可以把多个组件共用的配置提取成一个混入对象
-
使用方式:
第一步定义混合:
{ 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'
//关闭Vue的生产提示
Vue.config.productionTip = false
// 全局混合,给所有的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
}
},
}
复制代码
3.6 插件
-
功能:用于增强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()
plugins.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)
})
复制代码
School.vue
<template>
<div>
<h2>学校名称:{{name | mySlice}}</h2>
<h2>学校地址:{{address}}</h2>
<button @click="test">点我测试一个hello方法</button>
</div>
</template>
<script>
export default {
name:'School',
data() {
return {
name:'尚硅谷atguigu',
address:'北京',
}
},
methods: {
test(){
this.hello()
}
},
}
</script>
复制代码
Student.vue
<template>
<div>
<h2>学生姓名:{{name}}</h2>
<h2>学生性别:{{sex}}</h2>
<input type="text" v-fbind:value="name">
</div>
</template>
<script>
export default {
name:'Student',
data() {
return {
name:'张三',
sex:'男'
}
},
}
</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>
复制代码
3.7 scoped样式
如果不同组件起了相同的样式名,会造成样式冲突,在App.vue中后import导入的组件样式会覆盖前面一个组件的同名样式,所以用scoped解决。最好不要再App.vue的style中加入scoped,因为他是汇总组件,写在其中的样式为公共样式。
- 作用:让样式在局部生效,防止冲突。
- 写法:
<style lang="less" scoped>
//lang =''规定了用什么来写style,不写默认为css
.demo{
background-color: pink;
}
</style>
3.8 TodoList案例
实现一个简单的记事本小Demo:Github仓库
-
组件化编码流程:
(1).拆分静态组件:组件要按照功能点拆分,命名不要与html元素冲突。
(2).实现动态组件:考虑好数据的存放位置,数据是一个组件在用,还是一些组件在用:
1).一个组件在用:放在组件自身即可。
2). 一些组件在用:放在他们共同的父组件上(状态提升)。
(3).实现交互:从绑定事件开始。
-
props适用于:
(1).父组件 ==> 子组件 通信
(2).子组件 ==> 父组件 通信(要求父先给子一个函数,然后子调用这个函数去传递数据给父组件)
1. 在父组件定义函数
methods: {
addTodo(todoObj) {
this.todos.unshift(todoObj);
},
},
2.将父组件函数传递给子组件
<MyHeader :addTodo="addTodo"></MyHeader>
3.子组件接收父组件传递的函数
props: ["addTodo"],
4.调用这个函数,通知App组件去添加一个todo对象
this.addTodo(todoObj);
复制代码
- 使用v-model时要切记:v-model绑定的值不能是props传过来的值,因为props是不可以修改的!
- props传过来的若是对象类型的值,修改对象中的属性时Vue不会报错,但不推荐这样做。
3.9 webStorage
- 存储内容大小一般支持5MB左右(不同浏览器可能还不一样)
- 浏览器端通过 Window.sessionStorage 和 Window.localStorage 属性来实现本地存储机制。
3. 相关API:
1. ```xxxxxStorage.setItem('key', 'value');```
该方法接受一个键和值作为参数,会把键值对添加到存储中,如果键名存在,则更新其对应的值。
值为字符串,如果存入的值为对象,则将其转换为字符串后存入
2. ```xxxxxStorage.getItem('person');```
该方法接受一个键名作为参数,返回键名对应的值。对象转字符串后存入,取出后需将其重新转化为对象
3. ```xxxxxStorage.removeItem('key');```
该方法接受一个键名作为参数,并把该键名从存储中删除。
4. ```xxxxxStorage.clear()```
该方法会清空存储中的所有数据。
复制代码
4. 备注:
-
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>
复制代码
3.10 组件的自定义事件
-
一种组件间通信的方式,适用于:子组件 ===> 父组件
-
使用场景:A是父组件,B是子组件,B想给A传数据,那么就要在A中给B绑定自定义事件(事件的回调在A中)。
-
绑定自定义事件:
-
第一种方式,在父组件中:
或
-
第二种方式,在父组件中:
<Demo ref="demo"/> ...... mounted(){ this.$refs.xxx.$on('atguigu',this.test) }
-
-
若想让自定义事件只能触发一次,可以使用
once
修饰符,或$once
方法。 -
触发自定义事件:
this.$emit('atguigu',数据)
-
解绑自定义事件
this.$off('atguigu')
-
组件上也可以绑定原生DOM事件,需要使用
native
修饰符,否则会被当成自定义事件。 -
注意:通过
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>
复制代码
3.11 全局事件总线(GlobalEventBus)
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)所有的组件都可以得到
复制代码
-
一种组件间通信的方式,适用于任意组件间通信。
-
安装全局事件总线:
new Vue({ ...... beforeCreate() { Vue.prototype.$bus = this //安装全局事件总线,$bus就是当前应用的vm }, ...... }) 复制代码
-
使用事件总线:
-
接收数据:A组件想接收数据,则在A组件中给$bus绑定自定义事件,事件的回调留在A组件自身。
methods(){ demo(data){......} } ...... mounted() { this.$bus.$on('xxxx',this.demo) //回调methods提供的demo方法或直接使用箭头函数 } 复制代码
-
提供数据:
//在提供数据的组件的methods中书写 this.$bus.$emit('xxxx',数据) 复制代码
-
-
最好在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>
复制代码
3.12 消息订阅与发布(pubsub)
1.这种方式的思想与全局事件总线很相似
2.它包含以下操作:
(1)订阅消息–对应绑定事件监听
(2)发布消息–分发事件
(3)取消消息订阅–解绑事件监听
3.需要引入一个消息订阅与发布的第三方实现库
1.在线文档
2.下载:npminstall-Spubsub-js
3.相关语法:
(1)import PubSub from ‘pubsub-js’//引入
(2)PubSub.subscribe(‘msgName’,functon(msgName,data){})订阅消息
(3)PubSub.publish(‘msgName’,data):发布消息,触发订阅的回调函数调用
(4)PubSub.unsubscribe(token):取消消息的订阅
- 一种组件间通信的方式,适用于任意组件间通信。
- 使用步骤:
- 安装pubsub:
npm i pubsub-js
- 在订阅和发布消息的文件中引入:
import pubsub from 'pubsub-js'
- 接收数据:A组件想接收数据,则在A组件中订阅消息,订阅的回调留在A组件自身。
- 安装pubsub:
methods: {
demo(msgName, data) {
console.log(
"有人发布了hello消息,hello消息的回调执行了",
msgName,
data,
this
);
},
},
......
this.pubId = pubsub.subscribe("hello", this.demo);
复制代码
- 提供数据:B组件传递数据,则在B组件中发布消息
methods: {
sendStudentName() {
// 发布消息:pubsub.publish(事件名,参数),
pubsub.publish("hello", 666);
},
},
复制代码
- 最好在beforeDestroy钩子中,用
PubSub.unsubscribe(pid)
去取消订阅。
Student.vue
<template>
<div class="student">
<h2>学生姓名:{{ name }}</h2>
<h2>学生性别:{{ sex }}</h2>
<button @click="sendStudentName">把学生名给School组件</button>
</div>
</template>
<script>
import pubsub from "pubsub-js";
// 引入pubsub-js,pubsub是一个对象
export default {
name: "Student",
data() {
return {
name: "张三",
sex: "男",
};
},
methods: {
sendStudentName() {
// 发布消息:pubsub.publish(事件名,参数),
pubsub.publish("hello", 666);
},
},
};
</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>
import pubsub from "pubsub-js";
// 引入pubsub-js,pubsub是一个对象
export default {
name: "School",
data() {
return {
name: "尚硅谷",
address: "北京",
};
},
methods: {
demo(msgName, data) {
console.log(
"有人发布了hello消息,hello消息的回调执行了",
msgName,
data,
this
);
},
},
mounted() {
/*订阅消息:pubsub.subscribe(消息名,回调函数function(消息名,传入的参数){
console.log('有人发布了hello消息,hello消息的回调执行了',msgName,data)
console.log(this);
这里this为undefined,想要避免有如下两种方法
})
*/
// 方法一:this调用methods方法
// this.pubId = pubsub.subscribe("hello", this.demo);
// 方法二:使用箭头函数
this.pubId = pubsub.subscribe("hello", (msgName, data) => {
console.log("有人发布了hello消息,hello消息的回调执行了", msgName, data);
console.log(this);
});
},
beforeDestroy() {
// 取消订阅
pubsub.unsubscribe(this.pubId);
},
};
</script>
<style scoped>
.school {
background-color: skyblue;
padding: 5px;
}
</style>
复制代码
剩余文件跟全局事件总线一致,只是不需要安装全局事件总线
3.13 .sync修饰符
3.14 nextTick
- 语法:
this.$nextTick(回调函数)
- 作用:在下一次 DOM 更新结束后执行其指定的回调。
- 什么时候用:当改变数据后,要基于更新后的新DOM进行某些操作时,要在nextTick所指定的回调函数中执行。
3.15 Vue封装的过度与动画
- 作用:在插入、更新或移除 DOM元素时,在合适的时候给元素添加样式类名。
- a图示:
-
写法:
-
准备好样式:
- 元素进入的样式:
- v-enter:进入的起点
- v-enter-active:进入过程中
- v-enter-to:进入的终点
- 元素离开的样式:
- v-leave:离开的起点
- v-leave-active:离开过程中
- v-leave-to:离开的终点
- 元素进入的样式:
-
使用``包裹要过度的元素,并配置name属性:
<transition name="hello"> <h1 v-show="isShow">你好啊!</h1> </transition> 复制代码
appear是页面第一次刷新时出现的样式:
- 备注:若有多个元素需要过度,则需要使用``,且每个元素都要指定
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>
复制代码
用第三方动画库实现:
<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>
复制代码