尚硅谷Vue3 笔记总结及代码-2

简介: 尚硅谷Vue3 笔记总结及代码-2

4.9 自定义hook函数



什么是hook?—— 本质是一个函数,把setup函数中使用到的Composition API(组合式API)进行了封装。


类似于vue2.x中的mixin。


自定义hook的优势:复用代码。 让setup中的逻辑更清楚易懂。


在工程目录下创建一个hooks文件夹,里面的文件命名规则useXxxx 明起意hooks/usePont.js

// 引入需要的组合
import {reactive, onBeforeMount, onBeforeUnmount} from "vue";
// 创建函数 点击函数并且暴露出去
export default function () {
  // 实现鼠标点击获取坐标数据
  let point = reactive({
    x: 0,
    y: 0
  })
  // 实现方法
  function doPoint(e) {
    point.x = e.pageX
    point.y = e.pageY
    console.log('点击坐标为:(' + e.pageX + ',' + e.pageY + ')')
  }
  // 调用生命周期钩子-- 挂载之前 添加事件
  onBeforeMount(() => {
    window.addEventListener('mousemove', doPoint)
  })
  // 调用生命周期钩子-- 卸载挂载之前 移除事件
  onBeforeUnmount(() => {
    window.removeEventListener('mousemove', doPoint)
  })
  // 必须返回point 不然没有数据传入,报错
  return point
}



CustomHooksDemo.vue

<!--
User:Shier
CreateTime:12:38
-->
<template>
  <h1>当前求和结果:{{ sum }}</h1><br>
  <button @click="sum++">sum+1</button>
  <hr>
  <h1>当前鼠标坐标为:({{ point.x }},{{point.y}})</h1><br>
</template>
<script>
  // 引入需要的组合
  import {ref} from "vue";
  import usePoint from "../hooks/usePoint";
  export default {
    name: "CustomHooksDemo",
    setup() {
      console.log('组合setup--------')
      // 监视的数据
      let sum = ref(0)
      // 调用引入的usePoint函数
      let point = usePoint()
      return {sum,point}
    },
  }
</script>


Test.vue

<!--
User:Shier
CreateTime:16:18
-->
<template>
  <h1>当前鼠标坐标为:({{ point.x }},{{ point.y }})</h1><br>
</template>
<script>
  // 引入需要的组合
  import usePoint from "../hooks/usePoint";
  export default {
    name: "Test",
    setup() {
      // 调用usePoint函数,使用里面的鼠标移动来获取到坐标
      const point = usePoint()
      return {point}
    }
  }
</script>


APP.vue

<!--Vue3的自定义hook-->
<template>
  <button @click="isShowDate = !isShowDate">隐藏/显示</button>
  <LifecycleDemo v-if="isShowDate"/>
  <hr>
  <Test/>
</template>
<script>
  // 引入组件
  import LifecycleDemo from "./components/CustomHooksDemo";
  import Test from "./components/Test";
  // 引入组合
  import {ref} from 'vue'
  export default {
    name: 'App',
    // 注册组件
    components: {LifecycleDemo,Test},
    setup() {
      let isShowDate = ref(true)
      return {
        isShowDate
      }
    }
  }
</script>



4.10 toRef


作用:创建一个 ref 对象,其value值指向另一个对象中的某个属性。


语法:const name = toRef(person,'name')


应用: 要将响应式对象中的某个属性单独提供给外部使用时。


扩展:toRefs与toRef功能一致,但可以批量创建多个 ref 对象,语法:toRefs(person)

<!--
User:Shier
CreateTime:12:38
-->
<template>
  <h1 v-show="person.name">姓名:{{person.name}}</h1><br>
  <h1 v-show="person.age">年龄:{{person.age}}</h1><br>
  <h1 v-show="person.job.salary">薪资:{{person.job.salary}}K</h1><br>
  <button @click="person.name+='~'">姓名修改</button>
  <button @click="person.age++">年龄增加</button>
  <button @click="person.job.salary++">薪资++</button>
</template>
<script>
  // 引入toRef、toRefs组合
  import {reactive,toRef,toRefs} from "vue";
  export default {
    name: "toRef",
    setup() {
      // 监视的数据
      let person = reactive({
        name: 'Shier',
        age: 19,
        job: {
          job1: '全栈',
          salary:88
        }
      })
      // toRef
      let nameRef = toRef(person,'name'); // 第一个参数为数据对象,第二个参数为数据对象的属性
      return {
        person,
        // toRef 写法
        name:toRef(person,'name'),
        salary: toRef(person.job,'salary'),
        // toRefs写法
        ...toRefs(person) // 将person中多个属性返回给模板使用
      }
    }
  }
</script>


5、其它 Composition API(组合API)

5.1 shallowReactive 与 shallowRef


shallowReactive:只处理对象最外层属性的响应式(浅响应式)。


shallowRef:只处理基本数据类型的响应式,不进行对象的响应式处理。


什么时候使用?


如果有一个对象数据,结构比较深, 但变化时只是外层属性变化 ===> shallowReactive。

如果有一个对象数据,后续功能不会修改该对象中的属性,而是生新的对象来替换 ===> shallowRef。

5.2 readonly 与 shallowReadonly


  • readonly: 让一个响应式数据变为只读的(深只读)。
  • shallowReadonly:让一个响应式数据变为只读的(浅只读)。
  • 应用场景: 不希望数据被修改时。
<!--
User:Shier
CreateTime:12:38
-->
<template>
  <h1>姓名:{{ name }}</h1><br>
  <h1>年龄:{{ age }}</h1><br>
  <h1>薪资:{{ job.job1.salary }}K</h1><br>
  <button @click="name+='~'">姓名修改</button>
  <button @click="age++">年龄增加</button>
  <button @click="job.job1.salary++">薪资++</button>
</template>
<script>
  // 引入组合
  import {reactive, toRefs, readonly,shallowReadonly} from "vue";
  export default {
    name: "toRef",
    setup() {
      // 监视的数据
      let person = reactive({
        name: 'Shier',
        age: 19,
        job: {
          job1: {
            jobs11: '全栈',
            salary: 88
          }
        }
      })
      // 全部只读的
      person = readonly(person)
      // 浅层的是只读,深层的为是可修改的
      person = shallowReadonly(person)
      return {
        person,
        // toRefs写法
        ...toRefs(person)
      }
    }
  }
</script>

5.3 toRaw 与 markRaw


toRaw:

作用:将一个由reactive生成的响应式对象转为普通对象。

使用场景:用于读取响应式对象对应的普通对象,对这个普通对象的所有操作,不会引起页面更新。

markRaw:

作用:标记一个对象,使其永远不会再成为响应式对象。

应用场景:

有些值不应被设置为响应式的,例如复杂的第三方类库等。

当渲染具有不可变数据源的大列表时,跳过响应式转换可以提高性能。

5.4 customRef


  • 作用:创建一个自定义的 ref,并对其依赖项跟踪和更新触发进行显式控制。有两个参数:
  • trigger():用来触发修改的内容,然后去更新模板
  • track():追踪
  • 必须具有返回值
  • 实现防抖效果:
<template>
  <input type="text" v-model="keyword">
  <h3>{{keyword}}</h3>
</template>
<script>
  import {ref,customRef} from 'vue'
  export default {
    name:'Demo',
    setup(){
      // let keyword = ref('hello') //使用Vue准备好的内置ref
      //自定义一个myRef
      function myRef(value,delay){
        let timer
        //通过customRef去实现自定义
        return customRef((track,trigger)=>{
          return{
            get(){
              track() //告诉Vue这个value值是需要被“追踪”的
              return value
            },
            set(newValue){
              clearTimeout(timer)
              timer = setTimeout(()=>{
                value = newValue
                trigger() //告诉Vue去更新界面
              },delay)
            }
          }
        })
      }
      let keyword = myRef('hello',500) //使用程序员自定义的ref
      return {
        keyword
      }
    }
  }
</script>



5.5 provide 与 inject


  • 作用:实现祖与后代组件间通信
  • 套路:父组件有一个 provide 选项来提供数据,后代组件有一个 inject 选项来开始使用这些数据
  • 具体写法:
  1. 祖组件中:
setup(){
  ......
    let car = reactive({name:'奔驰',price:'40万'})
    provide('car',car)
    ......
}

后代组件中:

setup(props,context){
  ......
    const car = inject('car')
    return {car}
  ......
}


具体的实现案例:

APP.vue 作为祖组件

<!--Vue3的自定义hook-->
<template>
  <div class="app">
    <h2> APP祖组件 爷爷:{{ name }}---年龄:{{ age }}</h2>
    <Child/>
  </div>
</template>
<script>
  // 引入组件
  import {reactive, provide} from "vue";
  import Child from "./components/Child";
  export default {
    name: 'App',
    components: {Child},
    setup() {
      let grandfather = reactive({name: '张三', age: 88})
      // 将数据提供出去
      provide('grandfather',grandfather)
      return {...grandfather}
    }
  }
</script>
<style scoped>
  .app {
    background-color: gray;
    padding: 10px;
  }
</style>


Child.vue 子组件

  • 不在子组件中注入祖组件中的属性
<!--
User:Shier
CreateTime:21:51
-->
<template>
  <div class="child">
    <h2> Child组件 儿子</h2>
    <Son/>
  </div>
</template>
<script>
  import {inject} from 'vue'
  import Son from './Son'
  export default {
    name: "Child",
    components:{Son},
  }
</script>
<style scoped>
  .child {
    background-color: orange;
    padding: 10px;
  }
</style>

Son.vue 孙组件

<!--
User:Shier
CreateTime:21:50
-->
<template>
  <div class="son">
    <h2> Son组件 我的爷爷名字:{{grandfather.name}}---爷爷年龄:{{grandfather.price}}</h2>
  </div>
</template>
<script>
  // 导入inject
  import {inject} from "vue";
  export default {
    name: "Son",
    setup(){
      // 将信息注入
      let grandfather = inject('grandfather')
      return{grandfather}
    }
  }
</script>
<style scoped>
  .son {
    background-color: green;
  }
</style>


5.6 响应式数据的判断API


isRef: 检查一个值是否为一个 ref 对象

isReactive: 检查一个对象是否是由 reactive 创建的响应式代理

isReadonly: 检查一个对象是否是由 readonly 创建的只读代理

isProxy: 检查一个对象是否是由 reactive 或者 readonly 方法创建的代理

<!--Vue3的API-->
<template>
  <h2> APP</h2>
</template>
<script>
  // 引入组件
  import {reactive, provide, ref, readonly, isProxy, isReadonly, isRef, isReactive} from "vue";
  export default {
    name: 'App',
    setup() {
      let demo = reactive({name: '张三', age: 88})
      let sum = ref(0)
      // 将数据提供出去
      let demoRef = isRef(demo)
      let demoReactive = isReactive(demo)
      let sumReactive = isReactive(sum)
      let sumReadOnly = isReadonly(demo)
      let demoProxy = isProxy(demo)
      console.log('demoReactive---', demoReactive)  // true
      console.log('demoRef---', demoRef) // false  由reactive创建
      console.log('sumReactive---', sumReactive) // false 由reactive创建
      console.log('sumReadOnly---', sumReadOnly) // false 可修改的
      console.log('demoProxy---', demoProxy) // true 由reactive创建 都是使用代理的
      return {...demo}
    }
  }
</script>

6、Composition API 的优势

1.Options API(配置项API) 存在的问题(Vue2)


使用传统OptionsAPI中,新增或者修改一个需求,就需要分别在data,methods,computed里修改 。



2.Composition API(组合API) 的优势(Vue3)

我们可以更加优雅的组织我们的代码,函数。让相关功能的代码更加有序的组织在一起。

7、新的组件

7.1 Fragment


  • 在Vue2中组件的结构必须有一个根标签
  • 在Vue3中: 组件可以没有根标签, 内部会将多个标签包含在一个Fragment虚拟元素中
  • 好处: 减少标签层级, 减小内存占用

7.2 Teleport(标签)

什么是Teleport?—— Teleport 是一种能够将我们的组件html结构移动到指定位置的技术。

<!--
User:Shier
CreateTime:12:42
-->
<template>
  <div>
    <button @click="isShowDialog=true">打开弹窗</button>
    <!-- 指定在哪个标签下面添加 -->
    <teleport to="body">
      <!--点击了按钮之后顺便携带弹窗属性-->
      <div v-if="isShowDialog" class="mask">
        <div class="dialog">
          <h2>弹窗</h2>
          <h3>文本内容</h3>
          <button @click="isShowDialog=false">关闭弹窗</button>
        </div>
      </div>
    </teleport>
  </div>
</template>
<script>
  import {ref} from "vue";
  export default {
    name: "Dialog",
    setup() {
      let isShowDialog = ref(false)
      return {isShowDialog}
    }
  }
</script>
<style scoped>
  .mask {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    background-color: rgb(0, 0, 0, 0.5);
  }
  .dialog {
    position: absolute;
    text-align: center;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 400px;
    height: 400px;
    background-color: #00a4ff;
  }
</style>



7.3 Suspense(标签)

  • 等待异步组件时渲染一些额外内容,让应用有更好的用户体验
  • 使用步骤:
  • 异步引入组件
// import Child from 'vue'// 静态引入
import {defineAsyncComponent} from 'vue'
const Child = defineAsyncComponent(()=>import('./components/Child.vue'))


使用Suspense包裹组件,并配置好defaultfallback

<template>
  <div class="app">
    <h3>我是App组件</h3>
    <Suspense>
      <template v-slot:default>
        <Child/>
      </template>
      <template v-slot:fallback>
        <h3>加载中.....</h3>
      </template>
    </Suspense>
  </div>
</template>


通过案例实现

Child.vue

<!--
User:Shier
CreateTime:21:51
-->
<template>
  <div class="child">
    <h2> Child儿子组件 </h2>
    {{sum}}
  </div>
</template>
<script>
  import {ref} from "vue";
  export default {
    name: "Child",
    // 异步
    async setup(){
      let sum = ref(0)
      let p = new Promise((resolve, reject)=>{
        setTimeout(()=>{
          resolve({sum})
        },2000)
      })
      return await p
    }
  }
</script>
<style scoped>
  .child {
    background-color: orange;
    padding: 10px;
  }
</style>


APP.vue

<!--Vue3的自定义hook-->
<template>
  <div class="app">
    <h3>我是App组件</h3>
    <Suspense>
      <template v-slot:default>
        <Child/>
      </template>
      <template v-slot:fallback>
        <h3>加载中.....</h3>
      </template>
    </Suspense>
  </div>
</template>
<script>
  // 引入组件
  //import Child from "./components/Child"; // 静态引入
  // 异步引入
  import {defineAsyncComponent} from 'vue'
  const Child = defineAsyncComponent(()=>import('./components/Child'))
  export default {
    name: 'App',
    components: {Child},
  }
</script>
<style scoped>
  .app {
    background-color: gray;
    padding: 10px;
  }
</style>

8、其他

8.1 全局API的转移

  • Vue 2.x 有许多全局 API 和配置。
  • 例如:注册全局组件、注册全局指令等。
//注册全局组件
Vue.component('MyButton', {
  data: () => ({
    count: 0
  }),
  template: '<button @click="count++">Clicked {{ count }} times.</button>'
})
//注册全局指令
Vue.directive('focus', {
  inserted: el => el.focus()
}


Vue3.0中对这些API做出了调整:

  • 将全局的API,即:Vue.xxx调整到应用实例(app)上


2.x 全局 API(Vue 3.x 实例 API (app)
Vue.config.xxxx app.config.xxxx
Vue.config.productionTip Vue3中移除
Vue.component app.component
Vue.directive app.directive
Vue.mixin app.mixin
Vue.use app.use
Vue.prototype app.config.globalProperties


8.2 其他改变

  • data选项应始终被声明为一个函数。
  • 过度类名的更改:
  • Vue2.x写法
.v-enter,
.v-leave-to {
  opacity: 0;
}
.v-leave,
.v-enter-to {
  opacity: 1;
}

Vue3.x写法

.v-enter-from,
.v-leave-to {
  opacity: 0;
}
.v-leave-from,
.v-enter-to {
  opacity: 1;
}


  • 移除keyCode作为 v-on 的修饰符,同时也不再支持config.keyCodes
  • 移除v-on.native修饰符
  • 父组件中绑定事件
<my-component
  v-on:close="handleComponentEvent"
  v-on:click="handleNativeClickEvent"
/>

子组件中声明自定义事件

<script>
  export default {
    emits: ['close']
  }
</script>
  • 移除过滤器(filter)

过滤器虽然这看起来很方便,但它需要一个自定义语法,打破大括号内表达式是 “只是 JavaScript” 的假设,这不仅有学习成本,而且有实现成本!建议用方法调用或计算属性去替换过滤器。

目录
相关文章
|
9天前
vue3【实战】语义化首页布局
vue3【实战】语义化首页布局
28 2
|
9天前
|
存储 容器
vue3【实战】来回拖拽放置图片
vue3【实战】来回拖拽放置图片
19 2
|
9天前
|
JavaScript 开发工具 开发者
vue3【提效】使用 VueUse 高效开发(工具库 @vueuse/core + 新增的组件库 @vueuse/components)
vue3【提效】使用 VueUse 高效开发(工具库 @vueuse/core + 新增的组件库 @vueuse/components)
32 1
|
4天前
【vue3】Argumnt of type ‘history:RouterHistory;}is not assignable to paraeter of type ‘RouterOptions‘.
【vue3】Argumnt of type ‘history:RouterHistory;}is not assignable to paraeter of type ‘RouterOptions‘.
6 0
|
4天前
|
JavaScript
【vue3】vue3中路由hash与History的设置
【vue3】vue3中路由hash与History的设置
9 0
|
4天前
|
编解码 前端开发
【Vue3】解决电脑分辨率125%、150%及缩放导致页面变形的问题
【Vue3】解决电脑分辨率125%、150%及缩放导致页面变形的问题
11 0
|
4天前
|
JavaScript
【vue】vue 在线编辑、实时预览的代码交互组件 vue-code-view
【vue】vue 在线编辑、实时预览的代码交互组件 vue-code-view
11 0
|
4天前
|
JavaScript
【vue】 vue 翻页时钟制作,vue2、vue3
【vue】 vue 翻页时钟制作,vue2、vue3
11 0
|
2天前
|
JavaScript
|
4天前
|
JavaScript
【vue】el-dialog 内的tinymce弹窗被遮挡的解决办法 及 tinymce打开弹出菜单后直接关闭对话组件,导致该弹出菜单残留
【vue】el-dialog 内的tinymce弹窗被遮挡的解决办法 及 tinymce打开弹出菜单后直接关闭对话组件,导致该弹出菜单残留
16 6