作用域插槽
-
作用:使用组件时,可以访问组件内部的数据
-
语法:
- 子组件插槽slot上绑定一个数据
- 父组件插槽接收,scope是自定义变量名
- 父组件会将插槽上绑定的所有数据收集到scope对象中
-
示范:
子组件:
<template> <div> <!-- 按钮标题 --> <div class="title"> <slot name="title"></slot> <span class="btn" @click="isShow = !isShow"> {{ isShow ? "收起" : "展开" }} </span> </div> <!-- 下拉内容 --> <div class="container" v-show="isShow"> <slot :row='text'>默认内容</slot> </div> </div> </template> <script> export default { data() { return { isShow: false, text: '我是一只小小鸟' }; }, }; </script> <style scoped> h3 { text-align: center; } .title { display: flex; justify-content: space-between; align-items: center; border: 1px solid #ccc; padding: 0 1em; } .title h4 { line-height: 2; margin: 0; } .container { border: 1px solid #ccc; padding: 0 1em; } .btn { /* 鼠标改成手的形状 */ cursor: pointer; } img { width: 50%; } </style>
父组件:
<template> <div id="container"> <div id="app"> <h3>案例:折叠面板</h3> <Pannel> <template v-slot:title> <h4>这是一只小青蛙</h4> </template> <template v-slot='ss'> <p>{{ss.row}}</p> </template> </Pannel> </div> </div> </template> <script> import Pannel from './components/Pannel.vue' export default { components: { Pannel }, data() { return { } } }; </script> <style> #app { width: 400px; margin: 20px auto; background-color: #fff; border: 4px solid blueviolet; border-radius: 1em; box-shadow: 3px 3px 3px rgba(0, 0, 0, 0.5); padding: 1em 2em 2em; } </style>
自定义指令
作用:当内置指令无法满足需求时使用
语法:
-
局部注册-语法
directives: {
指令名字: {
inserted(el){
/对el进行操作
}
}
} -
全局注册-语法
//Vue.directive(指令名,对像)
Vue.directive('focus',{
inserted(el){
el.focus()
}
}
获取DOM($refs)
-
作用:通过id域ref属性获取原生DOM
-
用途:调用组件里的属性/方法
-
在mounted生命周期-2种方式获取原生D0M标签
-
使用方法:
1.目标标签-添加id/ref
<h1 ref="myH1" id="h"> 1.ref/id获取原生dom</h1>
2.怡当时机,通过id/通过ref属性获取目标标签
mounted(){
console.log(document.getElementById("h"));
console.log(this.$refs.myH1);
}
$nextTick
-
作用:修改完数据后,立即获取到更新后的DOM
-
this.$nextTick()/传入一个回调函数,该回调函数在下一次DOM更新结束后触发
Vue中DOM更新是异步的
this.$nextTick(()=>{
//在下一次DOM更新后触发
console.log(this.Srefs.cuteP.innerHTML)
}) -
$nextTick返回的是Promse
-
替代方法:await+ async优化 $nextTick