自定义指令
基础语法
自定义指令:自己定义的指令,可以封装一些dom操作,扩展额外功能
需求:当页面加载时,让元素获得焦点(autofocus 在 safari 浏览器有兼容性)
操作dom:dom元素.focus()
mounted (){
this.$refs.inp.focus()
}
- 全局注册—语法
vue.directives:('指令名',{
"inserted" (el) {
// 可以对 el 标签,扩展额外功能
el.focus()
}
})
inserted:
- 生命周期钩子
- 表示:当前指令所绑定的元素被添加到页面中会自动调用
- 局部注册—语法
//在Vue组件的配置项中
directives: {
"指令名": {
inserted () {
// 可以对 el 标签,扩展额外功能
el.focus()
}
}
}
使用:
<input v-指令名 type="text">
全局注册示例:
App.vue
<template>
<div>
<h1>自定义指令</h1>
<input v-focus ref="inp" type="text">
</div>
</template>
<script>
export default {
// mounted(){
// this.$refs.inp.focus()
// }
//可以使用mounted也可用全局注册
}
</script>
<style>
</style>
main.js
import Vue from 'vue'
import App from './App'
import router from './router'
Vue.config.productionTip = false
//全局注册指令
Vue.directive('focus',{
//inserted会在指令所在的元素被插入页面中时触发
inserted(el){
//el就是指令所绑定的元素
// console.log(el)
el.focus()
}
})
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
局部注册示例:
App.vue
<template>
<div>
<h1>自定义指令</h1>
<input v-focus ref="inp" type="text">
</div>
</template>
<script>
export default {
// mounted(){
// this.$refs.inp.focus()
// }
//局部注册指令
directives:{
//指令名:指令的配置项
focus:{
inserted(el){
el.focus()
}
}
}
}
</script>
<style>
</style>
指令的值
需求:实现一个 color 指令 - 传入不同的颜色, 给标签设置文字颜色
语法:在绑定指令时,可以通过 “等号” 的形式为指令 绑定 具体的参数值
-
v-指令名="指令值",通过等号可以绑定指令的值 如
<div v-coler="color>我是内容</div>" -
通过
binding.value可以拿到指令值,指令值修改会 触发 update 函数 -
通过update钩子,可以监听指令值的变化,进行dom更新操作
directives: {
color: {
inserted (el, binding) {
el.style.color = binding.value
},
update (el, binding) {
el.style.color = binding.value
}
}
}
示例:
App.vue
<template>
<div>
<h1 v-color="color1">指令的值1测试</h1>
<h1 v-color="color2">指令的值2测试</h1>
</div>
</template>
<script>
export default {
data () {
return {
color1: 'red',
color2: 'orange'
}
},
directives: {
color: {
// 1. inserted 提供的是元素被添加到页面中时的逻辑
inserted (el, binding) {
// console.log(el, binding.value);
// binding.value 就是指令的值
el.style.color = binding.value
},
// 2. update 指令的值修改的时候触发,提供值变化后,dom更新的逻辑
update (el, binding) {
console.log('指令的值修改了');
el.style.color = binding.value
}
}
}
}
</script>
<style>
</style>
- inserted 提供的是元素被添加到页面中时的逻辑
- update 指令的值修改的时候触发,提供值变化后,dom更新的逻辑(值修改视图更新)
效果图如下:
封装v-loading指令
v-loading指令封装
场景:实际开发过程中,发送请求需要时间,在请求的数据未回来时,页面会处于 空白状态 => 用户体验不好
需求:封装一个 v-loading 指令,实现加载中的效果
分析
1.本质 loading效果就是一个蒙层,盖在了盒子上
2.数据请求中,开启loading状态,添加蒙层
3.数据请求完毕,关闭loading状态,移除蒙层
实现
1.准备一个类名 loading,通过伪元素定位,设置宽高,实现蒙层
2.开启关闭 loading状态(添加移除蒙层),本质只需要添加移除类即可
3.利用指令语法,封装v-loading 通用指令
- inserted钩子中,binding.value 判断指令的值,设置默认状态
- update钩子中,判断指令的值,更新类名状态
示例:
App.vue
<template>
<div class="main">
<div class="box" v-loading="isLoading">
<ul>
<li v-for="item in list" :key="item.id" class="news">
<div class="left">
<div class="title">{{ item.title }}</div>
<div class="info">
<span>{{ item.source }}</span>
<span>{{ item.time }}</span>
</div>
</div>
<div class="right">
<img :src="item.img" alt="">
</div>
</li>
</ul>
</div>
<div class="box2" v-loading="isLoading2"></div>
</div>
</template>
<script>
// 安装axios => yarn add axios
import axios from 'axios'
// 接口地址:http://hmajax.itheima.net/api/news
// 请求方式:get
export default {
data () {
return {
list: [],
isLoading: true,
isLoading2: true
}
},
async created () {
// 1. 发送请求获取数据
const res = await axios.get('http://hmajax.itheima.net/api/news')
setTimeout(() => {
// 2. 更新到 list 中,用于页面渲染 v-for
this.list = res.data.data
this.isLoading = false
}, 2000)
},
directives: {
loading: {
inserted (el, binding) {
binding.value ? el.classList.add('loading') : el.classList.remove('loading')
},
update (el, binding) {
binding.value ? el.classList.add('loading') : el.classList.remove('loading')
}
}
}
}
</script>
<style>
.loading:before {
content: '';
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
background: #fff url('./loading.gif') no-repeat center;
}
.box2 {
width: 400px;
height: 400px;
border: 2px solid #000;
position: relative;
}
.box {
width: 800px;
min-height: 500px;
border: 3px solid orange;
border-radius: 5px;
position: relative;
}
.news {
display: flex;
height: 120px;
width: 600px;
margin: 0 auto;
padding: 20px 0;
cursor: pointer;
}
.news .left {
flex: 1;
display: flex;
flex-direction: column;
justify-content: space-between;
padding-right: 10px;
}
.news .left .title {
font-size: 20px;
}
.news .left .info {
color: #999999;
}
.news .left .info span {
margin-right: 20px;
}
.news .right {
width: 160px;
height: 120px;
}
.news .right img {
width: 100%;
height: 100%;
object-fit: cover;
}
</style>
插槽
默认插槽
插槽基本语法
场景:当组件内某一部分结构不确定,想要自定义时,用插槽slot占位封装
- 组件内需要定制的结构部分,改用
<slot></slot>占位 - 使用组件时,
<MyDialog></MyDialog>标签内部, 传入结构替换slot - 给插槽传入内容时,可以传入纯文本、html标签、组件
示例:
在需要定制的位置,使用slot占位
在使用组件时,组件标签内填入内容
App.vue
<template>
<div>
<!-- 2. 在使用组件时,组件标签内填入内容 -->
<MyDialog>
<div>你确认要删除么</div>
</MyDialog>
<MyDialog>
<p>你确认要退出么</p>
</MyDialog>
</div>
</template>
<script>
import MyDialog from './components/MyDialog.vue'
export default {
data () {
return {
}
},
components: {
MyDialog
}
}
</script>
<style>
body {
background-color: #b3b3b3;
}
</style>
MyDialog.vue
<template>
<div class="dialog">
<div class="dialog-header">
<h3>友情提示</h3>
<span class="close">✖️</span>
</div>
<div class="dialog-content">
<!-- 1. 在需要定制的位置,使用slot占位 -->
<slot></slot>
</div>
<div class="dialog-footer">
<button>取消</button>
<button>确认</button>
</div>
</div>
</template>
<script>
export default {
data () {
return {
}
}
}
</script>
<style scoped>
* {
margin: 0;
padding: 0;
}
.dialog {
width: 470px;
height: 230px;
padding: 0 25px;
background-color: #ffffff;
margin: 40px auto;
border-radius: 5px;
}
.dialog-header {
height: 70px;
line-height: 70px;
font-size: 20px;
border-bottom: 1px solid #ccc;
position: relative;
}
.dialog-header .close {
position: absolute;
right: 0px;
top: 0px;
cursor: pointer;
}
.dialog-content {
height: 80px;
font-size: 18px;
padding: 15px 0;
}
.dialog-footer {
display: flex;
justify-content: flex-end;
}
.dialog-footer button {
width: 65px;
height: 35px;
background-color: #ffffff;
border: 1px solid #e1e3e9;
cursor: pointer;
outline: none;
margin-left: 10px;
border-radius: 3px;
}
.dialog-footer button:last-child {
background-color: #007acc;
color: #fff;
}
</style>
后备内容
插槽的后备内容:封装组件时,可以为预留的 <slot> 插槽提供后备内容(默认内容)。
语法: 在 <slot> 标签内,放置内容, 作为默认显示内容
示例:
App.vue
<template>
<div>
<MyDialog></MyDialog>
<MyDialog>
你确认要退出么
</MyDialog>
</div>
</template>
<script>
import MyDialog from './components/MyDialog.vue'
export default {
data () {
return {
}
},
components: {
MyDialog
}
}
</script>
<style>
body {
background-color: #b3b3b3;
}
</style>
MyDialog.vue
<template>
<div class="dialog">
<div class="dialog-header">
<h3>友情提示</h3>
<span class="close">✖️</span>
</div>
<div class="dialog-content">
<!-- 往slot标签内部,编写内容,可以作为后备内容(默认值) -->
<slot>
我是默认的文本内容
</slot>
</div>
<div class="dialog-footer">
<button>取消</button>
<button>确认</button>
</div>
</div>
</template>
<script>
export default {
data () {
return {
}
}
}
</script>
<style scoped>
* {
margin: 0;
padding: 0;
}
.dialog {
width: 470px;
height: 230px;
padding: 0 25px;
background-color: #ffffff;
margin: 40px auto;
border-radius: 5px;
}
.dialog-header {
height: 70px;
line-height: 70px;
font-size: 20px;
border-bottom: 1px solid #ccc;
position: relative;
}
.dialog-header .close {
position: absolute;
right: 0px;
top: 0px;
cursor: pointer;
}
.dialog-content {
height: 80px;
font-size: 18px;
padding: 15px 0;
}
.dialog-footer {
display: flex;
justify-content: flex-end;
}
.dialog-footer button {
width: 65px;
height: 35px;
background-color: #ffffff;
border: 1px solid #e1e3e9;
cursor: pointer;
outline: none;
margin-left: 10px;
border-radius: 3px;
}
.dialog-footer button:last-child {
background-color: #007acc;
color: #fff;
}
</style>
具名插槽
需求:一个组件内有多处结构,需要外部传入标签进行定制
语法:
- 多个slot使用name属性区分名字
- template配合v-slot:名字来分发对应标签
- v-slot:插槽名可简化为#插槽名
示例:
MyDialong.vue
<template>
<div class="dialog">
<div class="dialog-header">
<!-- 一旦插槽起了名字,就是具名插槽,只支持定向分发 -->
<slot name="head"></slot>
</div>
<div class="dialog-content">
<slot name="content"></slot>
</div>
<div class="dialog-footer">
<slot name="footer"></slot>
</div>
</div>
</template>
<script>
export default {
data () {
return {
}
}
}
</script>
<style scoped>
* {
margin: 0;
padding: 0;
}
.dialog {
width: 470px;
height: 230px;
padding: 0 25px;
background-color: #ffffff;
margin: 40px auto;
border-radius: 5px;
}
.dialog-header {
height: 70px;
line-height: 70px;
font-size: 20px;
border-bottom: 1px solid #ccc;
position: relative;
}
.dialog-header .close {
position: absolute;
right: 0px;
top: 0px;
cursor: pointer;
}
.dialog-content {
height: 80px;
font-size: 18px;
padding: 15px 0;
}
.dialog-footer {
display: flex;
justify-content: flex-end;
}
.dialog-footer button {
width: 65px;
height: 35px;
background-color: #ffffff;
border: 1px solid #e1e3e9;
cursor: pointer;
outline: none;
margin-left: 10px;
border-radius: 3px;
}
.dialog-footer button:last-child {
background-color: #007acc;
color: #fff;
}
</style>
App.vue
<template>
<div>
<MyDialog>
<!-- 需要通过template标签包裹需要分发的结构,包成一个整体 -->
<template v-slot:head>
<div>我是大标题</div>
</template>
<template v-slot:content>
<div>我是内容</div>
</template>
<template #footer>
<button>取消</button>
<button>确认</button>
</template>
</MyDialog>
</div>
</template>
<script>
import MyDialog from './components/MyDialog.vue'
export default {
data () {
return {
}
},
components: {
MyDialog
}
}
</script>
<style>
body {
background-color: #b3b3b3;
}
</style>
作用域插槽
- 插槽分类
-
默认插槽(组件内定制一处的结构)
-
具名插槽(组件内定制多处的结构)
作用域插槽不属于插槽的一种分类,是插槽的一个传参语法
-
作用域插槽:定义slot 插槽的同时, 是可以 传值的 ,给 插槽 上可以 绑定数据,将来 使用组件时可以用
-
场景:封装表格组件
- 父传子 动态渲染表格内容
- 利用默认插槽,定制操作列
- 删除或者查看都需要用到 当前项的id,属于组件内部的数据 通过作用域插槽传值绑定,进而使用
基本使用步骤:
-
给 slot 标签, 以 添加属性的方式传值
<slot :id="item.id" msg="测试文本"></slot> -
所有添加的属性, 都会被收集到一个对象中
{ id: 3, msg: '测试文本' } -
在template中, 通过
#插槽名= "obj"接收,默认插槽名为default<MyTable :list="list"> <template #default="obj"> <button @click="del(obj.id)">删除</button> </template> </MyTable>
示例:
App.vue
<template>
<div>
<MyTable :data="list">
<!-- 3. 通过template #插槽名="变量名" 接收 -->
<template #default="obj">
<button @click="del(obj.row.id)">
删除
</button>
</template>
</MyTable>
<MyTable :data="list2">
<template #default="{ row }">
<button @click="show(row)">查看</button>
</template>
</MyTable>
</div>
</template>
<script>
import MyTable from './components/MyTable.vue'
export default {
data () {
return {
list: [
{ id: 1, name: '李明德', age: 27 },
{ id: 2, name: 'iu', age: 30 },
{ id: 3, name: '李钟硕', age: 34 },
],
list2: [
{ id: 1, name: '魏哲鸣', age: 33 },
{ id: 2, name: '李明德', age: 27 },
{ id: 3, name: 'iu', age: 30 },
]
}
},
methods: {
del (id) {
this.list = this.list.filter(item => item.id !== id)
},
show (row) {
// console.log(row);
alert(`姓名:${row.name}; 年纪:${row.age}`)
}
},
components: {
MyTable
}
}
</script>
Mytable.vue
<template>
<table class="my-table">
<thead>
<tr>
<th>序号</th>
<th>姓名</th>
<th>年纪</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item, index) in data" :key="item.id">
<td>{{ index + 1 }}</td>
<td>{{ item.name }}</td>
<td>{{ item.age }}</td>
<td>
<!-- 1. 给slot标签,添加属性的方式传值 -->
<slot :row="item" msg="测试文本"></slot>
<!-- 2. 将所有的属性,添加到一个对象中 -->
<!--
{
row: { id: 2, name: '孙大明', age: 19 },
msg: '测试文本'
}
-->
</td>
</tr>
</tbody>
</table>
</template>
<script>
export default {
props: {
data: Array
}
}
</script>
<style scoped>
.my-table {
width: 450px;
text-align: center;
border: 1px solid #ccc;
font-size: 24px;
margin: 30px auto;
}
.my-table thead {
background-color: #1f74ff;
color: #fff;
}
.my-table thead th {
font-weight: normal;
}
.my-table thead tr {
line-height: 40px;
}
.my-table th,
.my-table td {
border-bottom: 1px solid #ccc;
border-right: 1px solid #ccc;
}
.my-table td:last-child {
border-right: none;
}
.my-table tr:last-child td {
border-bottom: none;
}
.my-table button {
width: 65px;
height: 35px;
font-size: 18px;
border: 1px solid #ccc;
outline: none;
border-radius: 3px;
cursor: pointer;
background-color: #ffffff;
margin-left: 5px;
}
</style>
效果图如下:
综合案例—商品列表
1.需求说明
- my-tag 标签组件封装
(1) 双击显示输入框,输入框获取焦点
(2) 失去焦点,隐藏输入框
(3) 回显标签信息
(4) 内容修改,回车 → 修改标签信息
- my-table 表格组件封装
(1) 动态传递表格数据渲染
(2) 表头支持用户自定义
(3) 主体支持用户自定义
my-tag 标签组件封装
- 创建组件 - 初始化
- 实现功能
(1) 双击显示,并且自动聚焦
`v-if v-else @dbclick` 操作 isEdit自动聚焦:
$nextTick => $refs获取到dom,进行focus获取焦点封装v-focus指令
(2)失去焦点,隐藏输入框
@blur 操作 isEdit 即可
@blur="isEdit = false"
(3) 回显标签信息
-
回显的标签信息是父组件传递过来的
-
v-model实现功能 (简化代码) v-model => :value 和 @input
-
组件内部通过props接收, :value设置给输入框
(4) 内容修改了,回车 => 修改标签信息
@keyup.enter, 触发事件 $emit('input', e.target.value)
示例:
App.vue
<template>
<div class="table-case">
<MyTable :data="goods">
<template #head>
<th>编号</th>
<th>名称</th>
<th>图片</th>
<th width="100px">标签</th>
</template>
<template #body="{ item, index }">
<td>{{ index + 1 }}</td>
<td>{{ item.name }}</td>
<td>
<img
:src="item.picture"
/>
</td>
<td>
<MyTag v-model="item.tag"></MyTag>
</td>
</template>
</MyTable>
</div>
</template>
<script>
//my-tag 标签组建的封装
import MyTag from './components/MyTag.vue'
import MyTable from './components/MyTable.vue'
export default {
name: 'TableCase',
components: {
MyTag,
MyTable
},
data () {
return {
// 测试组件功能的临时数据
tempText: '水杯',
tempText2: '钢笔',
goods: [
{ id: 101, picture: 'https://yanxuan-item.nosdn.127.net/f8c37ffa41ab1eb84bff499e1f6acfc7.jpg', name: '梨皮朱泥三绝清代小品壶经典款紫砂壶', tag: '茶具' },
{ id: 102, picture: 'https://yanxuan-item.nosdn.127.net/221317c85274a188174352474b859d7b.jpg', name: '全防水HABU旋钮牛皮户外徒步鞋山宁泰抗菌', tag: '男鞋' },
{ id: 103, picture: 'https://yanxuan-item.nosdn.127.net/cd4b840751ef4f7505c85004f0bebcb5.png', name: '毛茸茸小熊出没,儿童羊羔绒背心73-90cm', tag: '儿童服饰' },
{ id: 104, picture: 'https://yanxuan-item.nosdn.127.net/56eb25a38d7a630e76a608a9360eec6b.jpg', name: '基础百搭,儿童套头针织毛衣1-9岁', tag: '儿童服饰' },
]
}
}
}
</script>
<style lang="less" scoped>
.table-case {
width: 1000px;
margin: 50px auto;
img {
width: 100px;
height: 100px;
object-fit: contain;
vertical-align: middle;
}
}
</style>
main.js
import Vue from 'vue'
import App from './App.vue'
Vue.config.productionTip = false
// 封装全局指令 focus
Vue.directive('focus', {
// 指令所在的dom元素,被插入到页面中时触发
inserted (el) {
el.focus()
}
})
new Vue({
render: h => h(App),
}).$mount('#app')
MyTable.vue
<template>
<table class="my-table">
<thead>
<tr>
<!-- 表头支持自定义 -->
<!-- 结构不能写死 - 多处结构自定义 【具名插槽】 -->
<slot name="head"></slot>
</tr>
</thead>
<tbody>
<!-- 数据不能写死,动态传递表格渲染的数据 props -->
<tr v-for="(item, index) in data" :key="item.id">
<slot name="body" :item="item" :index="index" ></slot>
</tr>
</tbody>
</table>
</template>
<script>
export default {
props: {
data: {
type: Array,
required: true
}
}
};
</script>
<style lang="less" scoped>
.my-table {
width: 100%;
border-spacing: 0;
img {
width: 100px;
height: 100px;
object-fit: contain;
vertical-align: middle;
}
th {
background: #f5f5f5;
border-bottom: 2px solid #069;
}
td {
border-bottom: 1px dashed #ccc;
}
td,
th {
text-align: center;
padding: 10px;
transition: all .5s;
&.red {
color: red;
}
}
.none {
height: 100px;
line-height: 100px;
color: #999;
}
}
</style>
MyTag.vue
<template>
<div class="my-tag">
<input
v-if="isEdit"
v-focus
ref="inp"
class="input"
type="text"
placeholder="输入标签"
:value="value"
@blur="isEdit = false"
@keyup.enter="handleEnter"
/>
<div
v-else
@dblclick="handleClick"
//双击显示
class="text">
{{ value }}
</div>
</div>
</template>
<script>
export default {
props: {
value: String
},
data () {
return {
isEdit: false
}
},
methods: {
handleClick () {
// 双击后,切换到显示状态 (Vue是异步dom更新)
this.isEdit = true
// // 等dom更新完了,再获取焦点
// this.$nextTick(() => {
// // 立刻获取焦点
// this.$refs.inp.focus()
// })
},
handleEnter (e) {
// 非空处理
if (e.target.value.trim() === '') return alert('标签内容不能为空')
// 子传父,将回车时,[输入框的内容] 提交给父组件更新
// 由于父组件是v-model,触发事件,需要触发 input 事件
this.$emit('input', e.target.value)
// 提交完成,关闭输入状态
this.isEdit = false
}
}
}
</script>
<style lang="less" scoped>
.my-tag {
cursor: pointer;
.input {
appearance: none;
outline: none;
border: 1px solid #ccc;
width: 100px;
height: 40px;
box-sizing: border-box;
padding: 10px;
color: #666;
&::placeholder {
color: #666;
}
}
}
</style>
效果如下:
my-table组件封装
数据不能写死,动态传递表格渲染的数据 props
结构不能写死 - 多处结构自定义 【具名插槽】
(1) 表头支持自定义
(2) 主体支持自定义
单页应用程序(SPA)
单页应用程序(SPA) : 所有功能在一个html页面上实现
优缺点:
-
优点:按需更新性能高,开发效率高,用户体验好
-
缺点:学习成本,首屏加载慢,不利于SEO(搜索引擎优化)
路由
生活中的路由:设备和ip的映射关系
Vue中的路由:路径 和 组件 的 映射关系
根据路由就能知道不同路径的,应该匹配渲染哪个组件
路由的基本使用
VueRouter 的介绍
作用:修改地址栏路径时,切换显示匹配的组件
说明:Vue 官方的一个路由插件,是一个第三方包
使用(5+2)
固定5个固定的步骤
-
下载 VueRouter 模块到当前工程,版本3.6.5
yarn add vue-router@3.6.5
Vue2 VueRouter3.x Vuex3.x Vue3 VueRouter4.x Vuex4.x
-
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')
此时,地址栏中显示/#/的效果,表示项目的路由已经被Vue-Router管理了
两个核心步骤
- 创建需要的组件(views目录),配置
路由规则routes
-
Find.vue My.vue Friend.vue
-
route 一条路由规则 { path: 地址栏路径, component: 组件 }
-
routes 路由规则们
import Find from './views/Find'
import My from './views/My'
import Friend from './views/Friend'
import VueRouter from 'vue-router'
const router = new VueRouter({
// routes 路由规则们
// route 一条路由规则 { path: 路径, component: 组件 }
//数组包对象
routes: [
{ path: '/find', component: Find },
{ path: '/my', component: My },
{ path: '/friend', component: Friend },
]
})
2.配置导航,配置路由出口(路径匹配的组件显示的位置router-view)
<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>
组件存放目录问题
注意: .vue文件本质无区别
组件分类
.vue文件分为两类,都是 .vue文件(本质无区别)
- 页面组件 (配置路由规则时使用的组件)
- 复用组件(多个组件中都使用到的组件)
分类放目的:更易维护
-
src/views文件夹
页面组件 - 页面展示 - 配合路由用
-
src/components文件夹
复用组件 - 展示数据 - 常用于复用