Vue3 demo初体验笔记 -Vue3跟Vue区别

2,861 阅读2分钟

zhuanlan.zhihu.com/p/184903118

先挂上giuhub地址,用Vue3做个ui库,欢迎star,佛系更新

Github:JamesLHY/vue3-ui

官网:Vite App

1.Vue 3 的 Template 支持多个根标签,Vue 2 不支持

2.Vue 3 有 createApp(),而 Vue 2 的是 new Vue()

createApp(组件),new Vue({template, render})

3.新 v-model 代替以前的 v-model 和 .sync

4.新增 context.emit,与 this.$emit 作用相同,前者写在setup(){}里面,后者写在methods里面

未完待续

继续更新

修改标题了

5.Vue 3 属性绑定

默认所有属性都绑定到根元素

使用 inheritAttrs: false 可以取消默认绑定

使用 $attrs 或者 context.attrs 获取所有属性

使用 v-bind="$attrs" 批量绑定属性

使用 const {size, level, ...xxx} = context.attrs 将属性分开

6.props V.S. attrs

props 要先声明才能取值,attrs 不用先声明

props 不包含事件,attrs 包含

props 没有声明的属性,会跑到 attrs 里

props 支持 string 以外的类型,attrs 只有 string 类型

未完待续

我又来了,更新了dialog组件

7.新组件Teleport

可以包裹住template,免受层叠上下文的影响,例子:

<div class='1' style='z-index:1'>
  <div>111</div>
</div>
<div class='2' style='z-index:2'></div>

如上例子,因为div2 的z-index 大于 div1 ,所以div1里面的111会被挡住。

vue3出了个新东西,Teleport

<Teleport to='body'>
<div class='1' style='z-index:1'>
   <div>111</div>
 </div>
 <div class='2' style='z-index:2'></div>
</Teleport>

用它包裹住加上参数to,可以使里面的内容自动加在to的下面,例子里就是加在body的下面,因此111会显示出来。

8.v-slot

vue3出了个新语法,可以在template后面加上参数 v-slot ,例子:

DialogDemo.vue

 <template v-slot:title>
 <strong>加粗的标题</strong>
 </template>

<template v-slot:content>
 <strong>hi</strong>
 <div>hi</div>
 </template>

Dialog.vue

<slot name="title"/>
 
<slot name="content"/>

在Dialog.vue里面申明slot的name,即可在DialogDemo.vue的template加上v-slot,里面标签很自由。

未完待续

好了我又来了
做的是tab组件,有兴趣的可以去上面的GitHub地址看看,总结了以下几点:

9.用 JS 获取插槽内容

const defaults = context.slots.default()

10.钩子

onMounted / onUpdated / watchEffect

前两者跟着前差不多

watchEffect介绍:

To apply and_automatically re-apply_ a side effect based on reactive state, we can use thewatchEffectmethod. It runs a function immediately while reactively tracking its dependencies and re-runs it whenever the dependencies are changed.

const count = ref(0)

watchEffect(() => console.log(count.value))
// -> logs 0

setTimeout(() => {
  count.value++
  // -> logs 1
}, 100)

[Computed and Watch | Vue.js​

v3.vuejs.org

](link.zhihu.com/?target=htt…)

功能就是类似把onMounted和onUpdated结合起来了

11.Typescript泛型

const indicator = ref <HTMLDivElement> (null)

可以通过 <> 给元素定型

12.获取宽高和位置

const { width, left } = el.getBoundingClientRect()

通过 getBoundingClientRect 获取元素的left,right,width,height

13.ES 6 析构赋值的重命名语法

const { left: left1 } = x. getBoundingClientRect()
const { left: left2 } = y. getBoundingClientRect()

es6析构赋值语法,可以通过用: 对相同类的给他起个新名字

以上就是关于tab组件的总结了,感觉跟vue3新语法有点偏离了,那就顺便也当作学一下es6跟ts吧

未完待续下次见

好家伙,我回来了。最近差不多把这个轮子造完了,官网装修也差不多了,不过也在debug中。

官网网址:Vite App

GitHub网址:JamesLHY/vue3-ui

有兴趣的朋友可以看看,如果有什么建议的话,欢迎提issue哦。

下面是官网的截图

特此感谢

@方应杭

提供的牛逼的教程