0、Vue是什么
Vue (读音 /vjuː/,类似于 view) 是一套用于构建用户界面的渐进式框架。与其它大型框架不同的是,Vue 被设计为可以自底向上逐层应用。Vue 的核心库只关注视图层,不仅易于上手,还便于与第三方库或既有项目整合。另一方面,当与现代化的工具链以及各种支持类库结合使用时,Vue 也完全能够为复杂的单页应用提供驱动。
1、起手
下面是Vue核心包开发 的入门案例,导包一定要正确。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<h2> val : {{ value }} </h2>
<span> <button @click="addbtn">点击 + 1</button></span>
</div>
<!-- 导入vue核心类库 -->
<script src="https://cdn.jsdelivr.net/npm/vue@2.7.14/dist/vue.js"></script>
<script>
const app = new Vue({
el: '#app', // 渲染div
data: {
value: 100 // 数据
},
methods: {
addbtn() { // 方法
this.value++
}
}
})
</script>
</body>
</html>
VueCli 自定义创建项目
npm i @vue/cli -g
vue create 名称
...
npm run serve
2、插值表达式
插值表达式是Vue 的模版语法,可以渲染出Vue 提供的数据(data, getters, computed等等)
语法: {{ 表达式 }}
表达式:是可以被求值的代码,JS引擎会讲其计算出一个结果
注意:
- 插值表达式中使用的数据 必须在data中进行了提供
- 不能使用 JavaScript 关键字,如for,if
- 不能在标签中用(可以用 :value="msg "进行绑定)
3、Vue的特征
1、响应式
4、指令快记
1、内容渲染指令(v-html、v-text)
<p v-text="uname">hello</p>
<p v-html="intro">hello</p>
2、条件判断指令
v-show = "表达式" // 控制display属性
v-if="表达式" // 控制是否创建节点
v-else-if="表达式" // 辅助v-if
v-else
3、事件绑定指令(v-on : 或者 @ )
- <button v-on:事件名="内联语句">按钮</button>
- <button v-on:事件名="处理函数">按钮</button>
- <button v-on:事件名="处理函数(实参)">按钮</button>
methods方法中可以直接使用 e 当做事件对象
如果传递了参数,则实参 `$event` 表示事件对象,固定用法
- @事件名.stop —> 阻止冒泡
- @事件名.prevent —>阻止默认行为
- @事件名.stop.prevent —>可以连用 即阻止事件冒泡也阻止默认行为
@click 单击 | @change 改变 |
---|---|
@dbclick 双击 | @submit 提交 |
@focus 获得焦点 | @keyup.enter 键起 |
@blur 失去焦点 |
4、属性绑定指令 (v-bind: 或者 :)
动态设置html的标签属性 比如:src、url、title
语法: **v-bind:**属性名=“表达式” 或者 :属性名=“表达式”
样式控制的增强
<div class="box" :class="{ 类名1: 布尔值, 类名2: 布尔值 }"></div> //一个类名,来回切换
<div class="box" :class="[ 类名1, 类名2, 类名3 ]"></div>
<div class="box" :style="{ CSS属性名1: CSS属性值, CSS属性名2: CSS属性值 }"></div>
5、双向绑定指令(v-model)
给 表单元素(input、radio、select)使用,双向绑定数据,可以快速 获取 或 设置 表单元素内容。
v-model.trim —>去除首位空格
v-model.number —>转数字
输入框 input:text ——> value
文本域 textarea ——> value
复选框 input:checkbox ——> checked
单选框 input:radio ——> checked
下拉菜单 select ——> value
v-model 是 @value + :input 的一个语法糖
<input v-model="msg" type="text">
<input :value="msg" @input="msg = $event.target.value" type="text">
6、列表渲染指令(v-for)
v-for="(item, index) in list" :key="item.id"
v-for="item in 10"
v-for="(key, value, index) in user"
- item 是数组中的每一项
- index 是每一项的索引,不需要可以省略
- arr 是被遍历的数组
- 可以遍历对象和数字
- item, index能用作表达式,插入{{ }} 中
5、computed计算属性
基于现有的数据,计算出来的新属性。 依赖的数据变化,自动重新计算。
语法
computed:{
计算属性名(){
// 代码逻辑
return 结果
}
}
computed:{
计算属性名: {
get () {
// 代码逻辑
return 结果
},
set (修改值) {
// 代码逻辑
}
}
}
3.注意
- 函数的写法,实则是属性
- computed中属性不能和data中的属性同名
- 使用computed中的计算属性和使用data中的属性是一样的用法
- computed中计算属性内部的this依然指向的是Vue实例
- 具有缓存特性,会对计算出来的结果缓存,使用会直接读取缓存
对象 | js中调用 | 模版调用 |
---|---|---|
computed计算属性 | this.计算属性 | {{计算属性}} |
methods计算属性 | this.方法名() | {{方法名()}} |
data属性 | this.属性 | {{ 属性}} |
6、watch监视器
监视数据变化,执行一些业务逻辑或异步操作
watch: {
数据属性名 (newValue, oldValue) {
一些业务逻辑 或 异步操作。
},
'对象.属性名' (newValue, oldValue) {
一些业务逻辑 或 异步操作。
}
}
完整写法:
watch: {
对象: {
deep: true, // 对复杂对象需要深度监视
immdiate:true,//立即执行handler函数
handler (newValue) {
console.log(newValue)
}
}
}
案例:
watch: {
// 该方法会在数据变化时调用执行
// newValue新值, oldValue老值(一般不用)
// words (newValue) {
// console.log('变化了', newValue)
// }
'obj.words' (newValue) {
// console.log('变化了', newValue)
// 防抖: 延迟执行 → 干啥事先等一等,延迟一会,一段时间内没有再次触发,才执行
clearTimeout(this.timer)
this.timer = setTimeout(async () => {
const res = await axios({
url: 'https://applet-base-api-t.itheima.net/api/translate',
params: {
words: newValue
}
})
this.result = res.data.data
console.log(res.data.data)
}, 300)
}
}
7、生命周期
8、工程化开发和脚手架
Vue CLI
基本介绍:
Vue CLI 是Vue官方提供的一个全局命令工具
可以帮助我们快速创建一个开发Vue项目的标准化基础架子。【集成了webpack配置】
好处:
- 开箱即用,零配置
- 内置babel等工具
- 标准化的webpack配置
使用步骤:
- 全局安装(只需安装一次即可) yarn global add @vue/cli 或者 npm i @vue/cli -g
- 查看vue/cli版本: vue --version
- 创建项目架子:vue create project-name(项目名不能使用中文)
- 启动项目:yarn serve 或者 npm run serve(命令不固定,找package.json)
目录结构:
9、组件化开发
-
三部分构成
-
template:结构 (有且只能一个根元素)
-
script: js逻辑
-
一个组件的 data 选项必须是一个函数。目的是为了:保证每个组件实例,维护独立的一份数据对象。
每次创建新的组件实例,都会新执行一次data 函数,得到一个新对象。
局部注册
1. 创建.vue 文件,驼峰命名格式
2. 导入在注册,使用
import 组件对象 from '@/components/vue文件路径'
import HmHeader from './components/HmHeader'
export default { // 局部注册
components: {
'组件名': 组件对象,
HmHeader:HmHeaer,
HmHeader
}
}
全局注册
1. 创建.vue组件
2. main.js 中进行全局注册
import HmButton from '@/components/HmButton'
Vue.component('HmButton', HmButton)
10、组件通信
组件通信,就是指组件与组件之间的数据传递
- 组件的数据是独立的,无法直接访问其他组件的数据。
- 想使用其他组件的数据,就需要组件通信
父组件通过props将数据传递给子组件
父向子传值步骤
- 给子组件以添加属性的方式传值
- 子组件内部通过props接收
- 模板中直接使用 props接收的值
子组件利用 $emit 通知父组件,进行修改更新
子向父传值步骤
- $emit触发事件,给父组件发送消息通知
- 父组件监听$emit触发的事件
- 提供处理函数,在函数的性参中获取传过来的参数
11、props
接收父组件或其他组件传递数据
- 可以 传递 任意数量 的prop
- 可以 传递 任意类型 的prop
props: ['username', 'age',....]
完整写法
props: {
校验的属性名: {
type: 类型, // Number String Boolean ...
required: true, // 是否必填
default: 默认值, // 默认值
validator (value) {
// 自定义校验逻辑
return 是否通过校验
}
}
},
12、ref和$refs
利用ref 和 $refs 可以用于 获取 dom 元素 或 组件实例
<div ref="chartRef">我是渲染图表的容器</div>
mounted () {
console.log(this.$refs.chartRef)
}
13、异步更新 & $nextTick
“显示之后”,立刻获取焦点是不能成功的!数据未渲染。
原因:Vue 是异步更新DOM (提升性能)
$nextTick:等 DOM更新后,才会触发执行此方法里的函数体
语法: this.$nextTick(函数体)
14、自定义指令
注册使用
-
内置指令:v-html、v-if、v-bind、v-on… 这都是Vue给咱们内置的一些指令,可以直接使用
-
自定义指令:同时Vue也支持让开发者,自己注册一些指令。这些指令被称为自定义指令。可以封装一些DOM操作,扩展额外的功能
全局注册:
//在main.js中
Vue.directive('指令名', {
"inserted" (el) {
// 可以对 el 标签,扩展额外功能
el.focus()
}
})
局部注册
//在Vue组件的配置项中
directives: {
"指令名": {
inserted (el) {
// 可以对 el 标签,扩展额外功能
el.focus()
}
}
}
inserted:被绑定元素插入父节点时调用的钩子函数
el:使用指令的那个DOM元素
传参
<div v-color="color">我是内容</div> // 通过=赋值
directives: {
color: {
inserted (el, binding) {
el.style.color = binding.value
},
update (el, binding) { //修改触发
el.style.color = binding.value
}
}
}
自定义封装:v-loading
步骤:
- 1.本质 loading效果就是一个蒙层,盖在了盒子上
- 2.数据请求中,开启loading状态,添加蒙层
- 3.数据请求完毕,关闭loading状态,移除蒙层
16、插槽-默认插槽
让组件内部的一些 结构 支持 自定义,只。 如弹框的对话内容。
步骤:
- 组件内需要定制的结构部分,改用****占位
- 使用组件时, ****标签内部, 传入结构替换slot
- 给插槽传入内容时,可以传入纯文本、html标签、组件
- 默认值:直接在slot中加入内容。如 默认值
17、插槽-具名插槽
完成多个位置的定制。
- 多个slot使用name属性区分名字
- template配合v-slot:名字来分发对应标签
MyDialog.vue
<div class="dialoa-header">
<slot name='head'> </slot>
</div>
app.vue:
<MyDialog>
<template v-slot:head>
插入值
</template>
<template #:head> //简写v-slot —> #
插入值
</template>
</MyDialog>
18、作用域插槽
一种传参语法, 给插槽绑定数据。
步骤:
给 slot 标签, 以 添加属性的方式传值
<slot :id="item.id" msg="测试文本"></slot>
所有添加的属性, 都会被收集到一个对象中(obj)
{ id: 3, msg: '测试文本' }
在template中, 通过 #插槽名= "obj"
接收,默认插槽名为 default
<MyTable :list="list">
<template #default="obj"> // 接收, obj.xxx访问
<button @click="del(obj.id)">删除</button>
</template>
</MyTable>
19、路由
修改地址栏路径时,切换显示匹配的组件
前五步5个固定的步骤(不用死背,熟能生巧)
-
下载 VueRouter 模块到当前工程,版本3.6.5
yarn add vue-router@3.6.5 npm i vue-router@3.6.5
-
main.js中引入VueRouter
import VueRouter from 'vue-router'
-
安装注册
Vue.use(VueRouter)
-
创建路由对象
const router = new VueRouter()
-
注入,将路由对象注入到new Vue实例中,建立关联
new Vue({ render: h => h(App), router:router }).$mount('#app')
当我们配置完以上5步之后 就可以看到浏览器地址栏中的路由 变成了 /#/的形式。表示项目的路由已经被Vue-Router管理了
6、创建需要的组件 (views目录),配置路由规则
7、配置导航,配置路由出口(路径匹配的组件显示的位置)
App.vue:
<div class="footer_wrap">
<a href="#/find">发现音乐</a>
<a href="#/my">我的音乐</a>
<a href="#/friend">朋友</a>
</div>
<div class="top">
<router-view></router-view>
</div>
20、声明式导航
导航链接 router-link
语法: <router-link to="path的值">发现音乐</router-link>
<div>
<div class="footer_wrap">
<router-link to="/find">发现音乐</router-link>
<router-link to="/my">我的音乐</router-link>
<router-link to="/friend">朋友</router-link>
</div>
<div class="top">
<!-- 路由出口 → 匹配的组件所展示的位置 -->
<router-view></router-view>
</div>
</div>
两个导航类名
router-link-exact-active
router-link-active
作用:
- 给任意一个class属性添加高亮样式
自定义设置:
const router = new VueRouter({
routes: [...],
linkActiveClass: "类名1",
linkExactActiveClass: "类名2"
})
情景处理
重定向
{ path: 匹配路径, redirect: 重定向到的路径 },
比如:
{ path:'/' ,redirect:'/home' }
找不到路径404,一般配置在路由规则的最后(都不匹配就报错)
import NotFind from '@/views/NotFind'
const router = new VueRouter({
routes: [
...
{ path: '*', component: NotFind } //最后一个
]
})
路由模式设置(默认挺好的)
- hash路由(默认) 例如: http://localhost:8080/#/home
- history路由(常用) 例如: http://localhost:8080/home
const router = new VueRouter({
mode:'histroy', //默认是hash
routes:[]
})
查询参数传参
-
查询参数传参
传参: <router-link to="/path?参数名=值"></router-link> 接收:$router.query.参数名
-
动态路由传参
在路由匹配规则中修改:path: '/search/:参数名' // 可选参数:在后面添加可选符"?" 传参:to='/path/参数值' 接收: $route.params.参数名
跳转方式
path路径跳转语法
//简单写法
this.$router.push('路由路径')
//完整写法
this.$router.push({
path: '路由路径'
})
name命名路由跳转。特点:适合 path 路径长的场景
-
路由规则,必须配置name配置项
{ name: '路由名', path: '/path/xxx', component: XXX },
-
通过name来进行跳转
this.$router.push({ name: '路由名' })
跳转传参总结:
- path路径跳转
-
query传参,接收:$router.query.参数名
this.$router.push('/路径?参数名1=参数值1&参数2=参数值2') this.$router.push({ path: '/路径', query: { 参数名1: '参数值1', 参数名2: '参数值2' } })
-
动态路由传参,接收:$route. params.参数值
this.$router.push('/路径/参数值') this.$router.push({ path: '/路径/参数值' })
- 命名路由跳转
-
query传参,接收:$router. query.参数值
this.$router.push({ name: '路由名字', query: { 参数名1: '参数值1', 参数名2: '参数值2' } })
-
动态路由传参 (需要配动态路由),接收:$route. params .参数值
this.$router.push({ name: '路由名字', params: { 参数名: '参数值', } })
21、Vuex 状态管理工具
Vuex 是一个插件,可以帮我们管理 Vue 通用的数据 (多组件共享的数据)。例如:购物车数据 个人信息数据
vuex起手
新建store/index.js:
import Vue from 'vue'
import Vuex from 'vuex'
// vuex也是vue的插件, 需要use一下, 进行插件的安装初始化
Vue.use(Vuex)
const store = new Vuex.Store()
export default store
main.js挂载Vuex
import store from './store'
new Vue({
render: h => h(App),
store // 挂载
}).$mount('#app')
核心概念-state
-
如何提供数据
// 创建仓库 store const store = new Vuex.Store({ // state 状态, 即数据, 类似于vue组件中的data, // 区别: 1.data 是组件自己的数据, 2.state 中的数据整个vue项目的组件都能访问到 strict: true // 开启严格模式,只允许mutations修改 state: { count: 101 } mutations: {} // 同步任务 })
-
如何访问Vuex中的数据
-
通过$store访问
获取 store: 1.Vue模板中获取 this.$store 2.js文件中获取 import store from "@/store" 模板中: {{ $store.state.xxx }} 组件逻辑中: this.$store.state.xxx JS模块中: store.state.xxx
-
通过辅助函数 mapState 获取 state中的数据
import { mapState } from 'vuex' // 一定是{ } computed: { ...mapState(['count']) } 直接使用 {{ count }} 或 this.count
-
核心概念-getters
需要从state中筛选出符合条件的一些数据,这些数据是依赖state的,此时会用到 getters
-
如何定义 getters数据
getters: { // getters函数的第一个参数是 state, (数据是依赖state的) // 必须要有返回值 filterList: state => state.list.filter(item => item > 5) }
-
如何使用 getters
-
this.$store
this.$store.getters.filterList
-
辅助函数- mapGetters
import { mapGetters } from 'vuex' computed: { ...mapGetters(['filterList']) }
-
核心概念-mutations
mutations是一个对象,对象中存放修改state的方法
-
如何定义 mutations 方法
mutations: { // 方法里参数 第一个参数是当前store的state属性 // payload 载荷 运输参数 调用mutaiions的时候 可以传递参数传递载荷 方法名 (state, 参数) { state.count += 1 } },
-
如何使用 mutations
-
this.$store
this.$store.commit('方法名',参数) // commit是固定的,只能一个参数,多属性写对象形式
-
辅助函数- mapMutations
import { mapMutations } from 'vuex' methods: { ...mapMutations(['addCount']) }
-
核心概念-actions
actions则负责进行异步操作
-
如何定义 actions方法
mutations: { changeCount (state, newCount) { state.count = newCount } } actions: { 方法名 (context, num) { // 一秒后, 给一个数, 去修改 num setTimeout(() => { context.commit('changeCount', num) }, 1000) } },
-
如何使用 actions
-
this.$store
this.$store.dispatch('方法名', 参数) // dispatch是固定的,只能一个参数,多属性写对象形式
-
辅助函数- mapActions
import { mapActions } from 'vuex' methods: { ...mapActions(['方法名']) }
-
小结
核心概念-module 模块化
代码模版
/store/mulules/user.js
const state = { userInfo: {name: 'zs', age: 18 }}
const mutations = {}
const actions = {}
const getters = {}
export default {
namespaced: true, //为辅助函数开启命名空间
state, mutations, actions, getters
}
/store/mulules/setting.js
const state = { theme: 'dark', desc: '描述真呀真不错'}
const mutations = {}
const actions = {}
const getters = {}
export default {
namespaced: true, //为辅助函数开启命名空间
state, mutations, actions, getters
}
/store/index.js
import user from './modules/user'
import setting from './modules/setting'
const store = new Vuex.Store({
modules:{ user, setting } // 引入两个模块
})
模块化使用表格
核心概念 | 位置 | 直接使用 | 辅助方法 |
---|---|---|---|
state | computed:{ } | $store.state.模块名.属性名 | mapState(‘模块名’, [‘xxx’,"xxx’…]) |
getters | computed:{ } | $store.getters[‘模块名/属性名’] | mapGetters(‘模块名’, [‘xxx’,"xxx’…]) |
mutations | methods:{ } | $store.commit(‘模块名/方法名’, 参数) | mapMutations(‘模块名’,[‘xxx’,"xxx’…]) |
actions | methods:{ } | $store.dispatch(‘模块名/方法名’, 参数) | mapActions(‘模块名’, [‘xxx’,"xxx’…]) |
提示:
-
import { mapXxxx, mapXxx } from ‘vuex’
-
…mapXxxx(‘模块名’, { 新的名字: 原来的名字 }),
-
组件中直接使用 属性
{{ age }}
或 方法@click="updateAge(2)"
namespaced: true, //为辅助函数开启命名空间
state, mutations, actions, getters
}
/store/index.js
import user from ‘./modules/user’
import setting from ‘./modules/setting’
const store = new Vuex.Store({
modules:{ user, setting } // 引入两个模块
})
#### **模块化使用表格**
| 核心概念 | 位置 | 直接使用 | 辅助方法 |
| --------- | ------------- | -------------------------------------- | -------------------------------------- |
| state | computed:{ } | $store.state.模块名.属性名 | mapState('模块名', ['xxx',"xxx'..]) |
| getters | computed:{ } | $store.getters['模块名/属性名'] | mapGetters('模块名', ['xxx',"xxx'..]) |
| mutations | methods:{ } | $store.commit('模块名/方法名', 参数) | mapMutations('模块名',['xxx',"xxx'..]) |
| actions | methods:{ } | $store.dispatch('模块名/方法名', 参数) | mapActions('模块名', ['xxx',"xxx'..]) |
提示:
- import { mapXxxx, mapXxx } from 'vuex'
- ...mapXxxx(**'模块名'**, { 新的名字: 原来的名字 }),
- 组件中直接使用 属性 `{{ age }}` 或 方法 `@click="updateAge(2)"`