手把手教你使用Vue2脚手架——入门学习笔记(附代码)

Vue CLI是一个基于 Vue.js 进行快速开发的完整系统,通过 @vue/cli现的交互式的项目脚手架

1. 初始化脚手架

1.首先(仅第一次执行)在终端执行npm install -g @vue/cli
全局安装@vue/cli

2.切换到你要创建项目的目录,然后使用命令创建项目 vue create xxxx
在这里插入图片描述
3.执行命令 npm run serve可以启动项目
在这里插入图片描述

2. 脚手架文件结构分析

使用命令创建项目 vue create xxxx创建项目后所得的脚手架文件结构如下所示。

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

示例:
在这里插入图片描述
1. 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>Joney</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>

2.这里我将原给的hello.vue组件 换成了 School.vuestudent.vue,在vue文件中可以写三个标签<template>页面模板、<script>模板对象和<style>样式。

如下是Scool.vue

<template>
	<div class="demo">
		<h2>学校名称:{{name}}</h2>
		<h2>学校地址:{{address}}</h2>
		<button @click="showName">点我提示学校名</button>	
	</div>
</template>

<script>
	 export default {
		name:'School',
		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:负责汇总所有组件

<template>
	<div>
		<img src="./assets/logo.png" alt="logo">
		<School></School>
		<Student></Student>
	</div>
</template>

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

	export default {
		name:'App',
		components:{
			School,
			Student
		}
	}
</script>

3.main.js是整个项目的入口文件

(1)vue.js是完整版的Vue,包含:核心功能+模板解析器import Vue from 'vue'这里引入的是vue.runtime.xxx.js,其是运行版的Vue,只包含:核心功能;没有模板解析器。

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

//引入Vue
import Vue from 'vue'
//引入App组件,它是所有组件的父组件
import App from './App.vue'
//关闭vue的生产提示
Vue.config.productionTip = false

//创建Vue实例对象---vm
new Vue({
	el:'#app',
	//render函数完成了这个功能:将App组件放入容器中
  render: h => h(App)
})

4.在执行npm run serve之前最好在vue.config.js 配置不检查语法错误。

module.exports={
    lintOnSave:false, //关闭语法检查
}

5.执行npm run serve启动项目,并打开该网页
在这里插入图片描述
在这里插入图片描述

3. ref属性

  1. ref属性被用来给元素子组件注册引用信息(id的替代者,获取标签),应用在html标签上获取的是真实DOM元素,应用在组件标签上是组件实例对象(vc)

  2. 使用方式
    (1)打标识:<h1 ref="xxx">.....</h1><School ref="xxx"></School>
    (2)获取:this.$refs.xxx
    在这里插入图片描述

  3. 代码

<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>

在这里插入图片描述

4. props配置项

1.功能:让组件接收外部传过来的数据,其优先级高。

2.传递数据<Demo name="xxx"/>这里age使用v-bind进行数据绑定,确保收到的内容是引号里的内容

<Student name="李四" sex="" :age="18"/>

3.接收数据

  • 第一种方式(只接收):props:['name']
props:['name','age','sex'] 
  • 第二种方式(限制类型):props:{name:String}
//接收的同时对数据进行类型限制
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
	}
}

4.代码
App.vue

<template>
	<div>
		<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>学生年龄:{{age}}</h2>
	</div>
</template>

<script>
	export default {
		name:'Student',
		data() {
			return {
				msg:'我是一个学生',
			}
		},
		//简单声明接收
		// 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>

在这里插入图片描述

5.注意

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

<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() {
			return {
				msg:'我是一个学生',
				myAge:this.age
			}
		},
		methods: {
			updateAge(){
				this.myAge++
			}
		},
		//接收的同时对数据:进行类型限制+默认值的指定+必要性的限制
		props:{
			name:{
				type:String, //name的类型是字符串
				required:true, //name是必要的
			},
			age:{
				type:Number,
				default:99 //默认值
			},
			sex:{
				type:String,
				required:true
			}
		}
	}
</script>

5. mixin混入

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

2.使用方式

(1)定义混合

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

(2)使用混入

  • 第一种:在student.vue中局部混入mixins:['xxx']
<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:'男',
				x:66
			}
		},
		// 配置
		mixins:[hunhe,hunhe2]
	}
</script>

注意: 当在student.vue混入对象中也有x数据时,以student.vue自身的为标准。但是对于生命周期钩子函数,student.vue混入对象中的都会生效。
在这里插入图片描述

  • 第二种:main.js中全局混入Vue.mixin(xxx)
//引入Vue
import Vue from 'vue'
//引入App
import App from './App.vue'

import {hunhe,hunhe2} from './mixin'
//关闭Vue的生产提示
Vue.config.productionTip = false

Vue.mixin(hunhe)
Vue.mixin(hunhe2)


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

6. 插件

1.功能用于增强Vue

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

3.定义插件(示例)

这里定义的所有东西,vm和组件实例对象(vc)都可以使用。

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('你好啊')}
	}
}

4.使用插件

main.js中通过import引入插件,并通过:Vue.use()使用

该方法需要在调用 new Vue() 之前被调用。

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

//应用(使用)插件
Vue.use(plugins,1,2,3)
//创建vm
new Vue({
	el:'#app',
	render: h => h(App)
})
// 在 School.vue中使用mySlice
<h2 @click="showName">学校名称:{{name | mySlice}}</h2>

7. scoped样式

1.作用:我们写的组件样式最终会汇总到一起,那么就可能存在类名相同的问题。scoped样式让样式在局部生效,防止冲突。

2.写法<style scoped>

<style scoped>
	.demo{
		background-color: skyblue;
	}
</style>

8. 组件化编码流程

1.组件化编码流程

(1) 实现静态组件:按照功能点拆分静态组件(命名不要与html元素冲突),实现静态页面效果。

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

  • 一个组件在用:放在组件自身即可。
  • 一些组件在用:放在他们共同的父组件上(状态提升)。

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

2.props适用于

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

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

3.使用v-model时要切记:v-model绑定的值不能是props传过来的值,因为props是不可以修改的!props传过来的若是对象类型的值,修改对象中的属性时Vue不会报错,但不推荐这样做!!!

9. webStorage

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

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

  • SessionStorage存储的内容会随着浏览器窗口关闭而消失
  • LocalStorage存储的内容,需要手动清除才会消失

3.SessionStorageLocalStorage可用API相同:

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

  • xxxxxStorage.getItem('person');接受一个键名作为参数,返回键名对应的值

  • xxxxxStorage.removeItem('key');接受一个键名作为参数,并把该键名从存储中删除

  • xxxxxStorage.clear()会清空存储中的所有数据。

4.代码演示

<!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)  // 得到字符串666
				localStorage.setItem('person',JSON.stringify(p))
			}
			function readData(){
				console.log(localStorage.getItem('msg'))
				console.log(localStorage.getItem('msg2'))
                
				const result = localStorage.getItem('person')
				console.log(JSON.parse(result))
			}
			function deleteData(){
				localStorage.removeItem('msg2')
			}
			function deleteAllData(){
				localStorage.clear()
			}
		</script>
	</body>
</html>

在这里插入图片描述

注意:

  • xxxxxStorage.getItem(xxx)如果xxx对应的value获取不到,那么getItem的返回值是null。
  • JSON.parse(null)的结果依然是null。

10. 组件的自定义事件

在没学自定义事件前,父子组件通信我们通过的是props。当子组件要给父组件通信时,需要父组件先声明一个函数,并把函数传给子组件,子组件调用该函数即可。

这个App.vue的代码,其定义了一个getSchoolName函数,然后通过v-bind将该函数传递给子组件student

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

<script>
	import School from './components/School'
  
	export default {
		name:'App',
		components:{School},
		methods: {
			getSchoolName(name){
				console.log('App收到了学校名:',name)
			},
	}
}
</script>

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

子组件student通过props配置收到getSchoolName函数,并给按钮绑定一个点击事件,当按钮被触发时,sendSchoolName函数调用this.getSchoolName(this.name),然后将参数传递给父组件App.

<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.现在通过 组件自定义事件 的方式,我们可以得到一种新的子组件 ===> 父组件的通信方式

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

3.绑定自定义事件

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

父亲给子组件绑定一个自定义事件@joney,当该事件被触发时调用getStudentName

<template>
	<div class="app">
		<!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第一种写法,使用@或v-on) -->
		<Student @joney="getStudentName"/>
	</div>
</template>

<script>
	import Student from './components/Student.vue'
  
	export default {
		name:'App',
		components:{Student},
		methods: {
			getStudentName(name){
				console.log('App收到了学生名:',name)
			},
	}
}
</script>

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

子组件绑定了一个点击事件,在sendStudentName中通过this.$emit('joney',this.name)触发了joney事件,并传递了参数this.namethis.$emit可以传递多个参数)

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

<script>
	export default {
		name:'Student',
		data() {
			return {
				name:'张三',
				sex:'男',
			}
		},
		methods: {
			sendStudentName(){
				//触发Student组件实例身上的joney事件,传递参数this.name
				this.$emit('joney',this.name)
			}
		},
	}
</script>

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

当我按下按钮时,可以收到学生的信息
在这里插入图片描述


在第二种方式,使用ref给子组件绑定一个自定义事件

App.vue中,我们给Student标签加上了 ref="student",然后在生命周期钩子函数mounted()中通过this.$refs.student.$on绑定了事件myjoney。

<template>
	<div class="app">
		<!-- 通过父组件给子组件绑定一个自定义事件实现:子给父传递数据(第二种写法,使用ref) -->
		<Student ref="student" />
	</div>
</template>

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

	export default {
		name:'App',
		components:{Student},
		methods: {
			getStudentName(name){
				console.log('App收到了学生名:',name)
			},
		},
		mounted() {
			this.$refs.student.$on('myjoney',this.getStudentName) //绑定自定义事件
			// this.$refs.student.$once(''myjoney',this.getStudentName) //绑定自定义事件(一次性)
		},
	}
</script>

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

在Student.vue中我们绑定一个点击事件,在点击事件中通过this.$emit('myjoney',this.name)激活函数

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

<script>
	export default {
		name:'Student',
		data() {
			return {
				name:'张三',
				sex:'男',
			}
		},
		methods: {
			sendStudentName(){
				//触发Student组件实例身上的myjoney事件,传递参数this.name
				this.$emit('myjoney',this.name)
			}
		},
		
	}
</script>

当我们点下按钮时,即可获得学生信息。
在这里插入图片描述

4.注意

  • 若想让自定义事件只能触发一次,可以使用once修饰符,或$once方法。
  • 触发自定义事件:this.$emit(''xxx,数据)
  • 解绑自定义事件this.$off('xxx'),若想解除Student身上自定义事件abc,可以参考如下语句。
  • 通过this.$refs.xxx.$on('atguigu',回调)绑定自定义事件时,回调要么配置在methods中,要么用箭头函数,否则this指向会出问题!
// 谁
this.$off('abc') //解绑一个自定义事件
this.$off(['abc','demo']) //解绑多个自定义事件
this.$off() //解绑所有的自定义事件

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

<Student ref="student" @click.native="show"/>

6.调用this.$destroy() 销毁了当前Student组件的实例,销毁后所有Student实例的自定义事件全都不奏效。

11. 全局事件总线

1.全局事件总线是一种组件间通信的方式,适用于任意组件间通信

安装全局事件总线

在Vue的原型上安装$bus,这样所有的组件对象实例vm都可以看到它,且可以通过它调用$on$off等函数

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

使用事件总线

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

 methods(){
   demo(data){......}
 }
 ......
 mounted() {
   this.$bus.$on('xxxx',this.demo)
 }

在School组件中,使用生命周期钩子函数mounted给$bus绑定自定义事件hello(使用的是箭头函数,这样里面的this指向就是School组件实例对象

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

<script>
	export default {
		name:'School',
		data() {
			return {
				name:'湖南大学',
				address:'湖南',
			}
		},
		//需要写成箭头函数
		mounted() {
			this.$bus.$on('hello',(data)=>{
				console.log('我是School组件,收到了数据',data)
			})
		},
		beforeDestroy() {
			this.$bus.$off('hello')
		},
	}
</script>

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

注意:最好在beforeDestroy钩子中,用$off去解绑当前组件所用到的事件

2.提供数据this.$bus.$emit('xxxx',数据)

在Student组件中通过this.$bus.$emit('hello',this.name)传递数据。

<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:'男',
			}
		},
		methods: {
			sendStudentName(){
				this.$bus.$emit('hello',this.name)
			}
		},
	}
</script>

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

按下按钮后,控制台显示学生数据。
在这里插入图片描述

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

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

2.使用步骤

(1)安装pubsubnpm i pubsub-js
在这里插入图片描述

(2)在订阅消息和发布消息的组件中都i引入: import pubsub from 'pubsub-js'

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

methods(){
  demo(data){......}
}
......
mounted() {
  this.pid = pubsub.subscribe('xxx',this.demo) //订阅消息
}

在School组件中通过pubsub.subscribe订阅了hello消息,且在函数中可接收到两个参数,一个是订阅的消息名字即hello和发布消息传递的参数。

注意:最好在beforeDestroy钩子中,调用pubsub.unsubscribe(this.pubId)取消消息订阅。

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

<script>
import pubsub from 'pubsub-js'
	export default {
		name:'School',
		data() {
			return {
				name:'湖南大学',
				address:'湖南',
			}
		},
		mounted() {
		// 箭头函数确保this指向为组件实例对象
		this.pubId=pubsub.subscribe('hello',(messageName,data)=>{
				console.log(this);
				console.log(messageName,data);
			})
		},
		beforeDestroy() {
			pubsub.unsubscribe(this.pubId)
		},
	}
</script>

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

(4)提供数据pubsub.publish('xxx',数据)

在Student组件中通过pubsub.publish('hello',666)发布消息,且传递参数为666.

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

<script>
	import pubsub from 'pubsub-js'
	export default {
		name:'Student',
		data() {
			return {
				name:'张三',
				sex:'男',
			}
		},
		methods: {
			sendStudentName(){
				pubsub.publish('hello',666)
			}
		},
	}
</script>

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

按下按钮后,获取发布的消息名字以及参数
在这里插入图片描述

13. Vue.nextTick( [callback, context] )

  1. 语法this.$nextTick(回调函数)
  2. 作用:在下一次 DOM 更新结束后执行其指定的回调。
  3. 应用场景当改变数据后,要基于更新后的新DOM进行某些操作时,要在nextTick所指定的回调函数中执行。 比如要给一个input框调用focus()函数聚焦,但是因为input框还没有放在页面上,所以需要把focus函数的调用放在Vue.nextTick的回调函数中。
	handleEdit(todo){
	···
	将input框显示在页面上
	···
	this.$nextTick(function(){
		this.$refs.inputTitle.focus() //聚焦
	})
},

14. Vue封装的过渡与动画

在没有学习Vue过渡与动画前,我们也可以通过css来进行实现动画效果,但是得写逻辑切换class类名为come或者go

<template>
	<div>
		<button @click="isShow = !isShow">显示/隐藏</button>
		<h1 v-show="isShow" class="come">你好呀</h1>
	</div>
</template>

<script>
	export default {
		name:'test1',
		data() {
			return {
				isShow:true
			}
		},
	}
</script>

<style scoped>
	h1{
		background-color: orange;
        width: 200px;
	}

	.come{
        animation:change 1s ;
    }
    .go{
        animation:change 1s  reverse;
    }

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

通过Vue封装的动画,我们可以更有效的实现效果

  • <transition> 元素作为单个元素/组件的过渡效果。
  • name 用于自动生成 CSS 过渡类名。例如:name: ‘hello’ 将自动拓展为 .hello-enter.hello-enter-active 等。默认类名为 “v”
  • appear 是否在初始渲染时使用过渡。默认为 false。

v-enter:进入的起点
v-enter-active:进入过程中
v-enter-to:进入的终点

v-leave:离开的起点
v-leave-active:离开过程中
v-leave-to:离开的终点

在这里插入图片描述

<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;
		width: 200px;
	}

	.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>

若有多个元素需要过渡,则需要使用:<transition-group>,且每个元素都要指定key值。 每个 <transition-group> 的子节点必须有独立的 key,动画才能正常工作。

<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">joney!</h1>
		</transition-group>
	</div>
</template>

<script>
	export default {
		name:'test1',
		data() {
			return {
				isShow:true
			}
		},
	}
</script>

<style scoped>
	h1{
		background-color: orange;
        width: 200px;
	}
	/* 进入的起点、离开的终点 */
	.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>

可以使用npm第三方库animate.css

  • 执行npm i animate.css下载第三方库
  • 执行import 'animate.css'导入库。
  • 使用相关类名
<template>
	<div>
		<button @click="isShow = !isShow">显示/隐藏</button>
		<transition-group 
			appear
			name="animate__animated animate__bounce" 
			enter-active-class="animate__swing"
			leave-active-class="animate__backOutUp"
		>
			<h1 v-show="!isShow" key="1">你好啊!</h1>
			<h1 v-show="isShow" key="2">joney!</h1>
		</transition-group>
	</div>
</template>

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

<style scoped>
	h1{
		background-color: orange;
        width: 200px;
	}
	

</style>
  • 8
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

焦妮敲代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值