cli安装和使用
1.如果下载缓慢请配置npm淘宝镜像npm config set registry http://registry.npm.taobao.org
2.全局安装 @vue/cli npm install -g @vue/cli
3.切换到创建项目的目录,使用命令创建项目vue create xxx
4.选择使用vue的版本
5.启动项目npm run serve
6.打包项目npm run build
7.暂停项目 Ctrl+C
注意
Vue脚手架隐藏了所有webpack相关的配置,若想查看具体的webpack配置,请执行
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: 包版本控制文件
render函数
mport Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
new Vue({
el:'#app',
// render函数功能:将App组件放入容器中
// 简写形式
render: h => h(App),
// 完整形式
// render(createElement){
// return createElement(App)
// }
})
不同版本的vue
- vue.js与vue.runtime.xxx.js的区别
avue.js 是完整版的Vue,包含:核心功能+模板解析器
bvue.runtime.xxx.js 是运行版的Vue,只包含核心功能,没有模板解析器
esm 就是 ES6 module - 因为 vue.runtime.xxx.js 没有模板解析器,所以不能使用template配置项,需要使用render函数接收到的createElement函数去指定具体内容
ref属性
ref
被用来给元素或子组件注册引用信息(id的替代者)
- 应用在html标签上获取的是真实DOM元素,应用在组件标签上获取的是组件实例对象vc
- 使用方式
a打标识:或
b获取: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>
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 配置项
props让组件接收外部传过来的数据
props适用于
a.父组件 ==> 子组件 通信
b.子组件 ==> 父组件 通信(要求父组件先给子组件一个函数)
使用方法:
- 传递数据这里age前加:,通过v-bind使得里面的18是数字
- 接收数据
第一种方式(只接收)props:[‘name’, ‘age’]
第二种方式(限制类型)props:{name:String, age:Number}
第三种方式(限制类型、限制必要性、指定默认值)
props: {
name: {
type: String, // 类型
required: true,// 必要性
default: 'cess'// 默认值
}
}
备注:props是只读的,Vue底层会监测你对props的修改,如果进行了修改,就会发出警告,若业务需求确实需要修改,那么请复制props的内容到data中,然后去修改data中的数据.
注意
1.使用v-model时要切记:v-model绑定的值不能是props传过来的值,因为props是不可以修改的
2.props传过来的若是对象类型的值,修改对象中的属性时Vue不会报错,但不推荐这样做
src/App.vue
<template>
<div>
<Student name="李四" sex="女" :age="18"/>
<Student name="王五" sex="男" :age="18"/>
</div>
</template>
<script>
import Student from './components/Student'
export default {
name:'App',
components:{ Student }
}
</script>
src/components/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: "我是一个UESTC大学的学生",
myAge: this.age,
};
},
methods: { updateAge() { this.myAge++; }, },
// 简单声明接收
// 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 混入
-
功能:可以把多个组件共用的配置提取成一个混入对象
-
使用方式
a. 定义混入const mixin = { data() {....}, methods: {....} .... }
b.使用混入
全局混入:Vue.mixin(xxx)
局部混入:mixins:[‘xxx’]
备注
1.组件和混入对象含有同名选项时,这些选项将以恰当的方式进行“合并”,在发生冲突时以组件优先
var mixin = {
data: function () {
return {
message: 'hello',
foo: 'abc'
}
}
}
new Vue({
mixins: [mixin],
data () {
return {
message: 'goodbye',
bar: 'def'
}
},
created () {
console.log(this.$data)
// => { message: "goodbye", foo: "abc", bar: "def" }
}
})
2.同名生命周期钩子将合并为一个数组,因此都将被调用。另外,混入对象的钩子将在组件自身钩子之前调用
var mixin = {
created () {
console.log('混入对象的钩子被调用')
}
}
new Vue({
mixins: [mixin],
created () {
console.log('组件钩子被调用')
}
})
// => "混入对象的钩子被调用"
// => "组件钩子被调用"
plugin 插件
1.功能:用于增强Vue
2.本质:包含install方法的一个对象,install的第一个参数是Vue,第二个以后的参数是插件使用者传递的数据
3.定义插件(见下 src/plugin.js)
4.使用插件:Vue.use()
src/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('你好啊')}
}
}
src/main.js
import Vue from 'vue'
import App from './App.vue'
import plugins from './plugins' // 引入插件
Vue.config.productionTip = false
Vue.use(plugins,1,2,3) // 应用(使用)插件
new Vue({
el:'#app',
render: h => h(App)
})
src/components/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>
src/components/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>
scoped样式
1.作用:让相同名称的样式只在当前组件生效,防止冲突
2.写法:
<template>
<div class="demo">
<h2 class="title">学校名称:{{ name }}</h2>
<h2>学校地址:{{ address }}</h2>
</div>
</template>
<script>
export default {
name:'School',
data() {
return {
name:'尚硅谷atguigu',
address:'北京',
}
}
}
</script>
<style scoped>
.demo{
background-color: skyblue;
}
</style>
本地存储
存储内容大小一般支持 5MB 左右(不同浏览器可能还不一样)
浏览器端通过Window.sessionStorage
和Window.localStorage
属性来实现本地存储机制
相关API
- xxxStorage.setItem(‘key’, ‘value’):该方法接受一个键和值作为参数,会把键值对添加到存储中,如果键名存在,则更新其对应的值
- xxxStorage.getItem(‘key’):该方法接受一个键名作为参数,返回键名对应的值
- xxxStorage.removeItem(‘key’):该方法接受一个键名作为参数,并把该键名从存储中删除
- xxxStorage.clear():该方法会清空存储中的所有数据
备注
- SessionStorage:存储的内容会随着浏览器窗口关闭而消失
- LocalStorage:存储的内容,需要手动清除才会消失
- xxxStorage.getItem(xxx):如果 xxx 对应的 value 获取不到,那么getItem()的返回值是null
- JSON.parse(null)的结果依然是null
localStorage
<h2>localStorage</h2>
<button onclick="saveDate()">点我保存数据</button><br/>
<button onclick="readDate()">点我读数据</button><br/>
<button onclick="deleteDate()">点我删除数据</button><br/>
<button onclick="deleteAllDate()">点我清空数据</button><br/>
<script>
let person = {name:"JOJO",age:20}
function saveDate(){
localStorage.setItem('msg','localStorage')
localStorage.setItem('person',JSON.stringify(person))
}
function readDate(){
console.log(localStorage.getItem('msg'))
const person = localStorage.getItem('person')
console.log(JSON.parse(person))
}
function deleteDate(){
localStorage.removeItem('msg')
localStorage.removeItem('person')
}
function deleteAllDate(){
localStorage.clear()
}
</script>
sessionStorage
<h2>sessionStorage</h2>
<button onclick="saveDate()">点我保存数据</button><br/>
<button onclick="readDate()">点我读数据</button><br/>
<button onclick="deleteDate()">点我删除数据</button><br/>
<button onclick="deleteAllDate()">点我清空数据</button><br/>
<script>
let person = {name:"JOJO",age:20}
function saveDate(){
sessionStorage.setItem('msg','sessionStorage')
sessionStorage.setItem('person',JSON.stringify(person))
}
function readDate(){
console.log(sessionStorage.getItem('msg'))
const person = sessionStorage.getItem('person')
console.log(JSON.parse(person))
}
function deleteDate(){
sessionStorage.removeItem('msg')
sessionStorage.removeItem('person')
}
function deleteAllDate(){
sessionStorage.clear()
}
</script>
组件的自定义事件
1.一种组件间通信的方式,适用于:子组件 ===> 父组件
2.使用场景:子组件想给父组件传数据,那么就要在父组件中给子组件绑定自定义事件(事件的回调在A中)
3.绑定自定义事件
a. 第一种方式,在父组件中<Demo @事件名=“方法”/>或<Demo v-on:事件名=“方法”/>
b. 第二种方式,在父组件中this.refs.demo.refs.demo.refs.demo.on(‘事件名’,方法)
<Demo ref="demo"/>
......
mounted(){
this.$refs.demo.$on('atguigu',this.test)
}
c 若想让自定义事件只能触发一次,可以使用once修饰符,或$once方法
- 触发自定义事件this.$emit(‘事件名’,数据)
- 解绑自定义事件this.$off(‘事件名’)
- 组件上也可以绑定原生DOM事件,需要使用native修饰符 @click.native=“show”
上面绑定自定义事件,即使绑定的是原生事件也会被认为是自定义的,需要加native,加了后就将此事件给组件的根元素 - 注意:通过this.refs.xxx.refs.xxx.refs.xxx.on(‘事件名’,回调函数)绑定自定义事件时,回调函数要么配置在methods中,要么用箭头函数,否则 this 指向会出问题
src/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"/> <!-- 🔴native -->
</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>
src/components/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(){
// 销毁了当前Student组件的实例,销毁后所有Student实例的自定义事件全都不奏效
this.$destroy()
}
},
}
</script>
<style lang="less" scoped>
.student{background-color: pink;padding: 5px;margin-top: 30px;}
</style>
全局事件总线
一种可以在任意组件间通信的方式,本质上就是一个对象,它必须满足以下条件
1.所有的组件对象都必须能看见他
2.这个对象必须能够使用on、on、on、emit、$off方法去绑定、触发和解绑事件
使用步骤
-
定义全局事件总线
new Vue({ ... beforeCreate() { Vue.prototype.$bus = this // 安装全局事件总线,$bus 就是当前应用的 vm }, ... })
-
使用事件总线
a.接收数据:A组件想接收数据,则在A组件中给$bus绑定自定义事件,事件的回调留在A组件自身
export default { methods(){ demo(data){...} } ... mounted() { this.$bus.$on('xxx',this.demo) } }
b.提供数据:this.bus.bus.bus.emit(‘xxx’,data)
-
最好在beforeDestroy钩子中,用$off()去解绑当前组件所用到的事件
示例
src/main.js
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
new Vue({
el:'#app',
render: h => h(App),
beforeCreate() {
Vue.prototype.$bus = this // 安装全局事件总线
}
})
src/App.vue
<template>
<div class="app">
<School/>
<Student/>
</div>
</template>
<script>
import Student from './components/Student'
import School from './components/School'
export default {
name:'App',
components:{ School, Student }
}
</script>
<style scoped>.app{background-color: gray;padding: 5px;}</style>
src/components/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");
},
};
</script>
<style scoped>.school {background-color: skyblue;padding: 5px;}</style>
src/components/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:'男'
}
},
methods: { //🔴
sendStudentName(){
this.$bus.$emit('demo', this.name)
}
}
}
</script>
<style scoped>.student{background-color: pink;padding: 5px;margin-top: 30px;}</style>
消息的订阅与发布
消息订阅与发布(pubsub)消息订阅与发布是一种组件间通信的方式,适用于任意组件间通信,需要用到第三方库实现,vue里面基本不用,因为全局事件总线就能实现。
1.安装pubsub:npm i pubsub-js
2.引入:import pubsub from ‘pubsub-js’
3.接收数据:A组件想接收数据,则在A组件中订阅消息,订阅的回调留在A组件自身
4.提供数据:pubsub.publish(‘xxx’,data)
5.最好在beforeDestroy钩子中,使用pubsub.unsubscribe(pid)取消订阅
nextTick
这是一个生命周期钩子
this.$nextTick
(回调函数)在下一次DOM更新结束后执行其指定的回调
什么时候用:当改变数据后,要基于更新后的新DOM进行某些操作时(例如获取焦点),要在nextTick所指定的回调函数中执行
src/components/MyItem.vue
<template>
<li>
<label>
<input type="checkbox" :checked="todo.done" @change="handleCheck(todo.id)"/>
<span v-show="!todo.isEdit">{{ todo.title }}</span>
<input type="text" v-show="todo.isEdit" :value="todo.title"
@blur="handleBlur(todo, $event)" ref="inputTitle"/>
</label>
<button class="btn btn-danger" @click="handleDelete(todo.id)">删除</button>
<button v-show="!todo.isEdit" class="btn btn-edit" @click="handleEdit(todo)">
编辑
</button>
</li>
</template>
<script>
export default {
name: "MyItem",
props: ["todo"], // 声明接收todo
methods: {
handleCheck(id) { // 勾选or取消勾选
// 通知App组件将对应的todo对象的done值取反
// this.checkTodo(id)
this.$bus.$emit("checkTodo", id);
},
handleDelete(id) { // 删除
if (confirm("确定删除吗?")) {
// 通知App组件将对应的todo对象删除
// this.deleteTodo(id)
this.$bus.$emit('deleteTodo',id)
}
},
handleEdit(todo) { // 编辑
if (todo.hasOwnProperty("isEdit")) {
todo.isEdit = true;
} else {
this.$set(todo, "isEdit", true);
}
this.$nextTick(function () {
this.$refs.inputTitle.focus();
});
},
handleBlur(todo, e) { // 失去焦点回调(真正执行修改逻辑)
todo.isEdit = false;
if (!e.target.value.trim()) return alert("输入不能为空!");
this.$bus.$emit("updateTodo", todo.id, e.target.value);
},
},
};
</script>
过渡与动画
Vue封装的过度与动画:在插入、更新或移除DOM元素时,在合适的时候给元素添加样式类名
写法
1.准备好样式
-
元素进入的样式
ⅰ.v-enter 进入的起点
ⅱ.v-enter-active 进入过程中
ⅲ.v-enter-to 进入的终点 -
元素离开的样式
ⅰ.v-leave 离开的起点
ⅱ.v-leave-active 离开过程中
ⅲ.v-leave-to 离开的终点
2.使用包裹要过度的元素,并配置name属性,此时需要将上面样式名的v换为name
3.要让页面一开始就显示动画,需要添加appear
<transition name="hello" appear>
<h1 v-show="isShow">你好啊!</h1>
</transition>
<style>
.hello-enter-active{
animation: hello 0.5s linear;
}
.hello-leave-active{
animation: hello 0.5s linear reverse;
}
@keyframes hello {
from{
transform: translateX(-100%);
}
to{
transform: translateX(0px);
}
}
</style>
4备注:若有多个元素需要过度,则需要使用,且每个元素都要指定key值
<transition-group name="hello" appear>
<h1 v-show="!isShow" key="1">你好啊!</h1>
<h1 v-show="isShow" key="2">尚硅谷!</h1>
</transition-group>
5第三方动画库Animate.css
<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">尚硅谷!</h1>
</transition-group>
slot 插槽
插槽:让父组件可以向子组件指定位置插入html结构,也是一种组件间通信的方式,适用于 父组件 ===> 子组件
-
1.分类:默认插槽、具名插槽、作用域插槽
-
2.使用方式
a.默认插槽
父组件中: <Category> <div>html结构1</div> </Category> 子组件中:Category <template> <div> <!-- 定义插槽 --> <slot>插槽默认内容...</slot> </div> </template>
b.具名插槽
父组件指明放入子组件的哪个插槽
slot="footer"
,如果是template
标签可以写成v-slot:footer
父组件中: <Category> <template slot="center"> <div>html结构1</div> </template> <template v-slot:footer> <div>html结构2</div> </template> </Category> 子组件中: <template> <div> <!-- 定义插槽 --> <slot name="center">插槽默认内容...</slot> <slot name="footer">插槽默认内容...</slot> </div> </template>
c作用域插槽
scope用于父组件往子组件插槽放的html结构接收子组件的数据
理解:数据在组件的自身,但根据数据生成的结构需要组件的使用者来决定,(games数据在Category组件中,但使用数据所遍历出来的结构由App组件决定)父组件中: <Category> <template scope="scopeData"> <!-- 生成的是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>
注意:关于样式,既可以写在父组件中,解析后放入子组件插槽;也可以放在子组件中,传给子组件再解析