gitee:课件、代码、资料
工具库推荐:
moment.js 时间处理工具,很强很大。还有个轻量的叫dayjs
生成全球唯一id工具:uuid,但是很大,有个精简版:nanoid
章节导航:
第 3 章:使用 Vue 脚手架
3.1 初始化脚手架
3.1.1. 说明
- Vue 脚手架是 Vue 官方提供的标准化开发工具(开发平台)。
- 最新的版本是 4.x。
- 文档: https://cli.vuejs.org/zh/。
3.1.2. 具体步骤
首先确保电脑安装了node.js,官网:https://nodejs.org/zh-cn/
配置 npm 淘宝镜像:npm config set registry https://registry.npm.taobao.org
第一步(仅第一次执行):全局安装@vue/cli。
npm install -g @vue/cli
第二步:切换到你要创建项目的目录
,然后使用命令创建项目
vue create 项目名称
第三步:启动项目
cd 进入项目目录
npm run serve
备注:
- 如出现下载缓慢请配置 npm 淘宝镜像:
npm config set registry https://registry.npm.taobao.org
- Vue 脚手架隐藏了所有 webpack 相关的配置,若想查看具体的 webpakc 配置,请执行:
vue inspect > output.js
3.1.3. 模板项目的结构
- node_modules
- public
- favicon.ico: 页签图标
index.html: 主页面
- src
- assets: 存放静态资源
- logo.png
component: 存放组件
- HelloWorld.vue
App.vue: 汇总所有组件
main.js: 入口文件
- assets: 存放静态资源
- .gitignore: git 版本管制忽略的配置
- babel.config.js: babel 的配置文件(es6转es5用的工具)
- package.json: 应用包配置文件(只要是符合npm规范的工程就会有这个包的说明书)
- package-lock.json:包版本控制文件
- README.md: 应用描述文件
main.js是入口文件,index.html没有引入main.js也能找到容器,都是脚手架配置好的
{
//你的包叫什么名字
"name": "vue_test",
//是什么版本
"version": "0.1.0",
"private": true,
//常用的命令
"scripts": {
//npm run serve 其实执行的就是"vue-cli-service serve"
//"serve" 开发的时候用
"serve": "vue-cli-service serve",
//"build" 构建,打包的时候用,转成HTML css js
"build": "vue-cli-service build",
//"lint" 进行语法检查
"lint": "vue-cli-service lint"
},
//采用的依赖,用了哪些库
"dependencies": {
"animate.css": "^4.1.1",
"axios": "^0.21.1",
"babel-preset-es2015": "^6.24.1",
"core-js": "^3.6.5",
"element-ui": "^2.15.3",
"less-loader": "^7.3.0",
"nanoid": "^3.1.23",
"pubsub-js": "^1.9.3",
"vue": "^2.6.11",
"vue-resource": "^1.5.3",
"vue-router": "^3.5.2",
"vuex": "^3.6.2"
},
}
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 %> 指的就是/public/这个路径,不要再写什么./ ../这种东西
vue底层是有处理的 -->
<link rel="icon" href="<%= BASE_URL %>favicon.ico">
<!-- 引入第三方样式 -->
<link rel="stylesheet" href="<%= BASE_URL %>css/bootstrap.css">
<!-- 配置网页标题 <%= htmlWebpackPlugin.options.title %> 是一个
插件的功能,从package.json中读取name属性作为网站的标题 -->
<title><%= htmlWebpackPlugin.options.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.1.4. 自己的额外笔记 render: h => h(App)
import Vue from 'vue'
能指定引用了哪个文件,是在\node_modules\vue\package.json
里的"module": "dist/vue.runtime.esm.js",
配置的,意思是如果通过es6的模块化语法去引入vue的时候,到底引入哪个js
vue.runtime.esm.js是一个精简版的vue,比完整版缺少了模板解析器,模板解析器占整个vue大约1/3的大小。
vue创建的时候会调用render(),render必须有返回值
render() 可以传一个参数,参数是一个function,通过console.log(typeof xx)可以在控制台打印xx的类型,看到是function
参数在官方文档叫 createElement
可以通过这个方法渲染具体内容
例如渲染一个h1标签,标签内容是’你好啊’ ,把createElement
创建完的元素返回,就可以在页面看到效果
"render": function render(createElement) {
return createElement('h1', '你好啊');
}
为什么用render不用template,因为webpack都打包完了,去掉模板解析器可以省一点空间
精简render过程:
键值同名,可以去掉引号省略
render(createElement) {
return createElement('h1', '你好啊');
}
没用到vm的this,所以可以写成箭头函数
render: (createElement) => {
return createElement('h1', '你好啊');
}
箭头函数里只有一个参数,省略小括号
render: createElement => {
return createElement('h1', '你好啊');
}
箭头函数里只有一句函数体,且要return,省略大括号和return
render: createElement => createElement('h1', '你好啊')
参数名起个短名
render: h => h('h1', '你好啊')
h1是HTML的内置标签,元素里要写具体内容所以传2个参数,如果是用app组件,那么:
render: h => h(App)
加引号表示是用HTML内置标签,不加引号用的是变量
带runtime的都是运行时vue,都是干掉了模板解析器的。
.vue文件中的 标签是由 package.json中的:
“devDependencies”: {
“vue-template-compiler”: “^2.6.11”
},
“vue-template-compiler” 库 来解析的
关于不同版本的Vue
- vue.js与vue.runtime.xxx.js的区别:
- vue.js是完整版的Vue,包含:核心功能 + 模板解析器。
- vue.runtime.xxx.js是运行版的Vue,只包含:核心功能;没有模板解析器。
- 因为vue.runtime.xxx.js没有模板解析器,所以不能使用template这个配置项,需要使用render函数接收到的createElement函数去指定具体内容。
vue.config.js配置文件
-
使用vue inspect > output.js可以查看到Vue脚手架的默认配置。
output.js 文件内部飘红是因为是个js文件,加个export default 或者 拿个变量接 const a =
改这个文件是不奏效的,只是展示看一下
写项目的时候,如果用默认配置,红框的都不能改,粉框随便改。报错信息:无法加载文件 C:\Users\Administrator\AppData\Roaming\npm\vue.ps1,因为在此系统中禁止执行脚本 原因分析:禁止执行脚本,那就打开权限执行脚本嘛 解决方案: 1. 打开 powerShell 用管理员身份运行 2.输入命令: set-ExecutionPolicy RemoteSigned 3.输入A 4.再输入 vue -V (搞定)
- 使用vue.config.js可以对脚手架进行个性化定制,详情见:https://cli.vuejs.org/zh
vue.config.js 和 代码中的Vue.config ↓ 没有任何关系,切勿搞混
//这是改vue构造函数身上的某个属性
Vue.config.productionTip = false
配置文件的暴露方式是module.exports = {} commonjs暴露,因为这个配置文件最终是输送给webpack,webpack基于nodejs,nodejs采用的模块化是commonjs。
最终我们写的配置文件会和默认配置合并,以我们写的优先。
ES6暴露 和 引入
多行暴露
导出
//a.js
export function aa1(){
console.log('分别导出1');
}
export function aa2(){
console.log('分别导出2');
}
导入
//index.js
//解构赋值
import { aa1 , aa2 } from 'a.js'
统一暴露
导出
//b.js
function bb1(){
console.log('综合导出1');
}
function bb2(){
console.log('综合导出2');
}
export {bb1,bb2}
导入
//index.js
//解构赋值
import {aa1,aa2} from 'b.js'
默认暴露
导出
//c.js
export default function cc(){
console.log('默认导出');
}
导入
//index.js
//使用定义变量
import c from 'c.js'
c.cc()
3.2 ref属性
- 被用来给元素或子组件注册引用信息(id的替代者)
- 应用在html标签上获取的是真实DOM元素,应用在组件标签上是组件实例对象(vc)
- 使用方式:
- 打标识:
<h1 ref="xxx">.....</h1>
或<School ref="xxx"></School>
- 获取:
this.$refs.xxx
- 打标识:
<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.3 props配置
-
功能:让组件接收外部传过来的数据
-
传递数据:
<Student name="李四" sex="女" :age="18"/>
像设置标签属性一样,引号里面是个字符串
如果用v-band(简写为:
):age=“18” ,那么引号里面就是个js表达式,18就是个数字 -
接收数据:
-
第一种方式(只接收):
props:['name','age','sex']
-
第二种方式(限制类型):
props:{name:String,age:Number,sex:String}
-
第三种方式(限制类型、限制必要性、指定默认值):
props:{ name:{ type:String, //类型 required:true, //必要性 default:'老王' //默认值 } }
备注:props是只读的,Vue底层会监测你对props的修改,如果进行了修改,就会发出警告,若业务需求确实需要修改,那么请复制props的内容到data中一份,然后去修改data中的数据。
如果props中的参数名和data中的变量名重名,以props中的为优先
要使用props中的参数直接this.xx即可,调用方法和data中一样
在标签中传参不允许用关键字,例如:ref、key等
-
3.4 mixin混入(混合)
-
功能:可以把多个组件共用的配置提取成一个混入对象
-
使用方式:
第一步定义混合:
创建一个.js文件,名字随意,可以叫mixin.js
export const hunhe = {
methods: {
showName(){
alert(this.name)
}
},
mounted() {
console.log('你好啊!')
},
}
export const hunhe2 = {
data() {
return {
x:100,
y:200
}
},
}
第二步使用混入:
局部混入:
<script>
//引入一个hunhe
import {hunhe,hunhe2} from '../mixin'
export default {
name:'School',
data() {
return {
name:'尚硅谷',
address:'北京',
x:666
}
},
mixins:[hunhe,hunhe2]
}
</script>
全局混入(在main.js中加入):
import {hunhe,hunhe2} from './mixin'
Vue.mixin(hunhe)
Vue.mixin(hunhe2)
-
注意事项:
混合里可以写 data()、methods、生命周期等
如果有冲突优先以引入方为准,但生命周期除外(会分别执行,先执行被引入方,再执行引入方。)
全局混合会在所有vm和vc中加入
3.5 插件
-
功能:用于增强Vue
-
本质:包含install方法的一个对象,install的第一个参数是Vue,第二个以后的参数是插件使用者传递的数据。
-
定义插件:
叫什么名都可以,可以叫plugins.js
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('你好啊')}
}
}
- 使用插件:
Vue.use()
在main.js中使用
//应用(使用)插件 可以使用多个
Vue.use(plugins,1,2,3)
Vue.use(plugins2)
Vue.use(plugins3)
3.6 scoped样式
如果要使用less,先要安装less,命令:npm i less-loader
如果安装报错,很可能是兼容性的问题,vue的脚手架要依托webpack,有可能会用一个旧一点的版本,在node_modules/中可以找到webpack/,打开package.json,看到用的是"version": “4.46.0”,现在最新的已经到5了,npm i less-loader默认安装最新的,最新的less是为了迎合webpack的更新,所以在4中用会报错。
用npm view webpack versions
命令可以看webpack 有多少版本
npm view less-loader versions
看less-loader的版本,安装7版本的就是和webpack4配合的
npm i less-loader@7
安装7版本最新的那个
- 作用:让样式在局部生效,防止冲突。
- 写法:
<style scoped>
3.7 总结TodoList案例
生成全球唯一id工具:uuid,但是很大,有个精简版:nanoid
npm i nanoid
,写法:引入inport {nanoid} from 'nanoid'
nanoid是用的分别暴露,暴露的是一个函数,使用的时候:nanoid()
修改数组可以整个替换,只要id正确
diff算法
不会出现效率问题
数组身上的reduce方法,是专门用来做条件统计的,前端做的工作就是把后端给的数据处理后显示,所以前端面试经常会问数组的方法。
//此处使用reduce方法做条件统计
//reduce第一个参数是个函数,第二个是初始值,pre是上一次统计的值(第一次循环就是给自己设置的初始值),current是遍历的每一个元素
//最终返回的值就是最后一次遍历return的值
const x = this.todos.reduce((pre, current) => {
//打印查看
console.log("@", pre, current);
//如果current.done 为true则+1,否则+0
return pre + (current.done ? 1 : 0);
}, 0);
//简写
return this.todos.reduce((pre, todo) => pre + (todo.done ? 1 : 0), 0);
计算属性允许套娃,用其他的计算属性算一个新的计算属性
代码:
MyFooter.vue
<template>
<div class="todo-footer" v-show="total">
<label>
<!-- <input type="checkbox" :checked="isAll" @change="checkAll"/> -->
<input type="checkbox" v-model="isAll"/>
</label>
<span>
<span>已完成{{doneTotal}}</span> / 全部{{total}}
</span>
<button class="btn btn-danger" @click="clearAll">清除已完成任务</button>
</div>
</template>
<script>
export default {
name:'MyFooter',
props:['todos','checkAllTodo','clearAllTodo'],
computed: {
//总数
total(){
return this.todos.length
},
//已完成数
doneTotal(){
//此处使用reduce方法做条件统计
/* const x = this.todos.reduce((pre,current)=>{
console.log('@',pre,current)
return pre + (current.done ? 1 : 0)
},0) */
//简写
return this.todos.reduce((pre,todo)=> pre + (todo.done ? 1 : 0) ,0)
},
//控制全选框
isAll:{
//全选框是否勾选
get(){
return this.doneTotal === this.total && this.total > 0
},
//isAll被修改时set被调用
set(value){
this.checkAllTodo(value)
}
}
},
methods: {
/* checkAll(e){
this.checkAllTodo(e.target.checked)
} */
//清空所有已完成
clearAll(){
this.clearAllTodo()
}
},
}
</script>
<style scoped>
/*footer*/
.todo-footer {
height: 40px;
line-height: 40px;
padding-left: 6px;
margin-top: 5px;
}
.todo-footer label {
display: inline-block;
margin-right: 20px;
cursor: pointer;
}
.todo-footer label input {
position: relative;
top: -1px;
vertical-align: middle;
margin-right: 5px;
}
.todo-footer button {
float: right;
margin-top: 5px;
}
</style>
MyHeader.vue
<template>
<div class="todo-header">
<input type="text" placeholder="请输入你的任务名称,按回车键确认" v-model="title" @keyup.enter="add"/>
</div>
</template>
<script>
import {nanoid} from 'nanoid'
export default {
name:'MyHeader',
//接收从App传递过来的addTodo
props:['addTodo'],
data() {
return {
//收集用户输入的title
title:''
}
},
methods: {
add(){
//校验数据
if(!this.title.trim()) return alert('输入不能为空')
//将用户的输入包装成一个todo对象
const todoObj = {id:nanoid(),title:this.title,done:false}
//通知App组件去添加一个todo对象
this.addTodo(todoObj)
//清空输入
this.title = ''
}
},
}
</script>
<style scoped>
/*header*/
.todo-header input {
width: 560px;
height: 28px;
font-size: 14px;
border: 1px solid #ccc;
border-radius: 4px;
padding: 4px 7px;
}
.todo-header input:focus {
outline: none;
border-color: rgba(82, 168, 236, 0.8);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(82, 168, 236, 0.6);
}
</style>
MyItem.vue
<template>
<li>
<label>
<input type="checkbox" :checked="todo.done" @change="handleCheck(todo.id)"/>
<!-- 如下代码也能实现功能,但是不太推荐,因为有点违反原则,因为修改了props -->
<!-- <input type="checkbox" v-model="todo.done"/> -->
<span>{{todo.title}}</span>
</label>
<button class="btn btn-danger" @click="handleDelete(todo.id)">删除</button>
</li>
</template>
<script>
export default {
name:'MyItem',
//声明接收todo、checkTodo、deleteTodo
props:['todo','checkTodo','deleteTodo'],
methods: {
//勾选or取消勾选
handleCheck(id){
//通知App组件将对应的todo对象的done值取反
this.checkTodo(id)
},
//删除
handleDelete(id){
if(confirm('确定删除吗?')){
//通知App组件将对应的todo对象删除
this.deleteTodo(id)
}
}
},
}
</script>
<style scoped>
/*item*/
li {
list-style: none;
height: 36px;
line-height: 36px;
padding: 0 5px;
border-bottom: 1px solid #ddd;
}
li label {
float: left;
cursor: pointer;
}
li label li input {
vertical-align: middle;
margin-right: 6px;
position: relative;
top: -1px;
}
li button {
float: right;
display: none;
margin-top: 3px;
}
li:before {
content: initial;
}
li:last-child {
border-bottom: none;
}
li:hover{
background-color: #ddd;
}
li:hover button{
display: block;
}
</style>
MyList.vue
<template>
<ul class="todo-main">
<MyItem
v-for="todoObj in todos"
:key="todoObj.id"
:todo="todoObj"
:checkTodo="checkTodo"
:deleteTodo="deleteTodo"
/>
</ul>
</template>
<script>
import MyItem from './MyItem'
export default {
name:'MyList',
components:{MyItem},
//声明接收App传递过来的数据,其中todos是自己用的,checkTodo和deleteTodo是给子组件MyItem用的
props:['todos','checkTodo','deleteTodo']
}
</script>
<style scoped>
/*main*/
.todo-main {
margin-left: 0px;
border: 1px solid #ddd;
border-radius: 2px;
padding: 0px;
}
.todo-empty {
height: 40px;
line-height: 40px;
border: 1px solid #ddd;
border-radius: 2px;
padding-left: 5px;
margin-top: 10px;
}
</style>
App.vue
<template>
<div id="root">
<div class="todo-container">
<div class="todo-wrap">
<MyHeader :addTodo="addTodo"/>
<MyList :todos="todos" :checkTodo="checkTodo" :deleteTodo="deleteTodo"/>
<MyFooter :todos="todos" :checkAllTodo="checkAllTodo" :clearAllTodo="clearAllTodo"/>
</div>
</div>
</div>
</template>
<script>
import MyHeader from './components/MyHeader'
import MyList from './components/MyList'
import MyFooter from './components/MyFooter.vue'
export default {
name:'App',
components:{MyHeader,MyList,MyFooter},
data() {
return {
//由于todos是MyHeader组件和MyFooter组件都在使用,所以放在App中(状态提升)
todos:JSON.parse(localStorage.getItem('todos')) || []
}
},
methods: {
//添加一个todo
addTodo(todoObj){
this.todos.unshift(todoObj)
},
//勾选or取消勾选一个todo
checkTodo(id){
this.todos.forEach((todo)=>{
if(todo.id === id) todo.done = !todo.done
})
},
//删除一个todo
deleteTodo(id){
this.todos = this.todos.filter( todo => todo.id !== id )
},
//全选or取消全选
checkAllTodo(done){
this.todos.forEach((todo)=>{
todo.done = done
})
},
//清除所有已经完成的todo
clearAllTodo(){
this.todos = this.todos.filter((todo)=>{
return !todo.done
})
}
},
watch: {
todos:{
deep:true,
handler(value){
localStorage.setItem('todos',JSON.stringify(value))
}
}
},
}
</script>
<style>
/*base*/
body {
background: #fff;
}
.btn {
display: inline-block;
padding: 4px 12px;
margin-bottom: 0;
font-size: 14px;
line-height: 20px;
text-align: center;
vertical-align: middle;
cursor: pointer;
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05);
border-radius: 4px;
}
.btn-danger {
color: #fff;
background-color: #da4f49;
border: 1px solid #bd362f;
}
.btn-danger:hover {
color: #fff;
background-color: #bd362f;
}
.btn:focus {
outline: none;
}
.todo-container {
width: 600px;
margin: 0 auto;
}
.todo-container .todo-wrap {
padding: 10px;
border: 1px solid #ddd;
border-radius: 5px;
}
</style>
-
组件化编码流程:
(1).拆分静态组件:组件要按照功能点拆分,命名不要与html元素冲突。
(2).实现动态组件:考虑好数据的存放位置,数据是一个组件在用,还是一些组件在用:
1).一个组件在用:放在组件自身即可。
2). 一些组件在用:放在他们共同的父组件上(
状态提升
)。 (3).实现交互:从绑定事件开始。
-
props适用于:
(1).父组件 ==> 子组件 通信
(2).子组件 ==> 父组件 通信(要求父先给子一个函数)
-
使用v-model时要切记:v-model绑定的值不能是props传过来的值,因为props是不可以修改的!
-
props传过来的若是对象类型的值,修改对象中的属性时Vue不会报错,但不推荐这样做。
-
数据在哪里,操作数据的方法就在哪里
3.8 webStorage
-
存储内容大小一般支持5MB左右(不同浏览器可能还不一样)
-
浏览器端通过 Window.sessionStorage 和 Window.localStorage 属性来实现本地存储机制。
-
相关API:
-
xxxxxStorage.setItem('key', 'value');
该方法接受一个键和值作为参数,会把键值对添加到存储中,如果键名存在,则更新其对应的值。 -
xxxxxStorage.getItem('person');
该方法接受一个键名作为参数,返回键名对应的值。
-
xxxxxStorage.removeItem('key');
该方法接受一个键名作为参数,并把该键名从存储中删除。
-
xxxxxStorage.clear()
该方法会清空存储中的所有数据。
-
-
备注:
- SessionStorage存储的内容会随着浏览器窗口关闭而消失。
- LocalStorage存储的内容,需要手动清除才会消失。
xxxxxStorage.getItem(xxx)
如果xxx对应的value获取不到,那么getItem的返回值是null。JSON.parse(null)
的结果依然是null。
3.9 组件的自定义事件
-
一种组件间通信的方式,适用于:子组件 ===> 父组件
-
使用场景:A是父组件,B是子组件,B想给A传数据,那么就要在A中给B绑定自定义事件(事件的回调在A中)。
-
绑定自定义事件:
-
第一种方式,在父组件中:
<Demo @atguigu="test"/>
或<Demo v-on:atguigu="test"/>
-
第二种方式,在父组件中:
<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指向会出问题!
代码:
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>
Student.vue
<template>
<div class="student">
<h2>学生姓名:{{name}}</h2>
<h2>学生性别:{{sex}}</h2>
<h2>当前求和为:{{number}}</h2>
<button @click="add">点我number++</button>
<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(){
//触发Student组件实例身上的atguigu事件
this.$emit('atguigu',this.name,666,888,900)
// this.$emit('demo')
// this.$emit('click')
},
unbind(){
this.$off('atguigu') //解绑一个自定义事件
// this.$off(['atguigu','demo']) //解绑多个自定义事件
// this.$off() //解绑所有的自定义事件
},
death(){
this.$destroy() //销毁了当前Student组件的实例,销毁后所有Student实例的自定义事件全都不奏效。
}
},
}
</script>
<style lang="less" scoped>
.student{
background-color: pink;
padding: 5px;
margin-top: 30px;
}
</style>
App.vue
<template>
<div class="app">
<h1>{{msg}},学生姓名是:{{studentName}}</h1>
<!-- 通过父组件给子组件传递函数类型的props实现:子给父传递数据 -->
<School :getSchoolName="getSchoolName"/>
<!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第一种写法,使用@或v-on) -->
<!-- <Student @atguigu="getStudentName" @demo="m1"/> -->
<!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第二种写法,使用ref) -->
<Student ref="student" @click.native="show"/>
</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){
console.log('App收到了学生名:',name,params)
this.studentName = name
},
m1(){
console.log('demo事件被触发了!')
},
show(){
alert(123)
}
},
mounted() {
this.$refs.student.$on('atguigu',this.getStudentName) //绑定自定义事件
// this.$refs.student.$once('atguigu',this.getStudentName) //绑定自定义事件(一次性)
},
}
</script>
<style scoped>
.app{
background-color: gray;
padding: 5px;
}
</style>
3.10 全局事件总线(GlobalEventBus)
要实现这个功能,首先要满足2点:1.所有vc都能看到。2.这个中间件要有
$on、$off、$emit
这些方法
首先解决第一点:把对象存到Vue原型对象上,vm和vc都可以通过原型链找到。可以把对象存到window,但是不建议。把对象存到组件构造函数也行不通,因为每次都是一个新的构造函数。
其实$on、$off、$emit
都是Vue原型对象上的方法。
解决第二点:可以通过Vue.extend方法生成一个组件的构造函数,再通过new的方式创建组件实例(实际写的时候vue也是通过new的方式创建的xx组件实例)
现在就可以在任何vc中通过this.x.$on()
方法绑定自定义事件了。
但不用写的那么麻烦,可以把vm存进去,利用生命周期钩子函数mounted()
在一开始,刚new Vue的时候,数据监测、数据代理还没有,模板也没开始解析,但是this的指向已经是vm实例本身了。
-
一种组件间通信的方式,适用于任意组件间通信
-
安装全局事件总线:
new Vue({ ...... beforeCreate() { //通常(规范)命名为$bus Vue.prototype.$bus = this //安装全局事件总线,$bus就是当前应用的vm }, ...... })
-
使用事件总线:
-
接收数据:A组件想接收数据,则在A组件中给$bus绑定自定义事件,事件的回调留在A组件自身。
methods:{ demo(data){......} } ...... mounted() { //xxx名称最好创建常量.js中保存 this.$bus.$on('xxxx',this.demo) }
-
提供数据:
this.$bus.$emit('xxxx',数据)
-
-
最好在beforeDestroy钩子中,用$off去解绑
当前组件所用到的
事件(之前的vc中绑定的自定义事件为什么不用解绑,因为vc销毁vc本身的自定义事件也会销毁,而现在这个是定义在公共组件中的不会随着某个组件的销毁而销毁)。
3.11 消息订阅与发布(pubsub)
-
一种组件间通信的方式,适用于
任意组件间通信
。 -
使用步骤:
-
安装pubsub:
npm i pubsub-js
-
引入:
import pubsub from 'pubsub-js'
-
接收数据:A组件想接收数据,则在A组件中订阅消息,订阅的回调留在A组件自身。
methods(){ demo(data){......} } ...... mounted() { this.pid = pubsub.subscribe('xxx',this.demo) //订阅消息 }
-
提供数据:
pubsub.publish('xxx',数据)
-
最好在beforeDestroy钩子中,用
PubSub.unsubscribe(pid)
去取消订阅。
-
3.12 nextTick
- 语法:
this.$nextTick(回调函数)
- 作用:在下一次 DOM 更新结束后执行其指定的回调。
- 什么时候用:当改变数据后,要基于更新后的新DOM进行某些操作时,要在nextTick所指定的回调函数中执行。
应用场景:例如v-show,要在一个方法中改变data数据来使页面元素显示隐藏,但是vue更新dom要在方法执行完,不会改一下数据更新一下,不然效率太低了。但是dom不更新,隐藏的输入框不显示,不现实就无法获取焦点,所以要用
$nextTick
方法。
用定时器也可以实现,不指定延迟时间setTimeout(() => { this.$refs.inputTitle.focus(); });
因为定时器就算立即执行,里面的回调也要推向队列去执行,也能实现。
this.$nextTick(function(){
this.$refs.inputTitle.focus()
})
Object.prototype.hasOwnProperty(‘xxx’)
hasOwnProperty() 方法会返回一个布尔值,指示对象自身属性中是否具有指定的属性(也就是,是否有指定的键)。
3.13 Vue封装的过度与动画
-
作用:在插入、更新或移除 DOM元素时,在合适的时候给元素添加样式类名。
-
图示:
-
写法:
-
准备好样式:
- 元素进入的样式:
- v-enter:进入的起点
- v-enter-active:进入过程中
- v-enter-to:进入的终点
- 元素离开的样式:
- v-leave:离开的起点
- v-leave-active:离开过程中
- v-leave-to:离开的终点
- 元素进入的样式:
-
使用
<transition>
包裹要过度的元素,并配置name属性,如果配了name,样式中的v-要改成name值-:<transition name="hello"> <h1 v-show="isShow">你好啊!</h1> </transition>
-
备注:若有多个元素需要过度,则需要使用:
<transition-group>
,且每个元素都要指定key
值。其他都一样 -
想进来就有动画效果给transition 加 appear 属性
<transition name="hello" appear></transition>
-
其实到底用过渡还是动画是我们决定的,vue就是封装了一个
<transition>
的组件,在特定的时候加上一些类名,类名对应的是过度还是动画等着我们去写 -
自己写动画只需要写v-enter-active, v-leave-active
-
<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;
}
.hello-leave-active{
animation: atguigu 0.5s linear reverse;
}
@keyframes atguigu {
from{
transform: translateX(-100%);
}
to{
transform: translateX(0px);
}
}
</style>
- 如果拿过渡写,则需要写完整6个样式
<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>
- 用第三方css库
//在下面js中引入
import 'animate.css'
//在html结构中加入
<transition
appear
//在html结构中加入这3行
name="animate__animated animate__bounce"
enter-active-class="animate__swing"
leave-active-class="animate__backOutUp"
>