Vue3快速上手

317 阅读8分钟

1.1 创建Vue3.0工程

1.1.1 使用 vue-cli 创建

官方文档:cli.vuejs.org/zh/guide/cr…

## 查看@vue/cli版本,确保@vue/cli版本在4.5.0以上
vue --version
## 安装或者升级你的@vue/cli
npm install -g @vue/cli
## 创建
vue create vue_test
## 启动
cd vue_test
npm run serve

1.2.2 使用 vite 创建

官方文档:v3.cn.vuejs.org/guide/insta…

vite官网:vitejs.cn

## 创建工程
npm init vite-app <project-name>
## 进入工程目录
cd <project-name>
## 安装依赖
npm install
## 运行
npm run dev

2.1 常用 Composition API

官方文档: v3.cn.vuejs.org/guide/compo…

2.1.1 setup

<h1>{{name}}</h1>   //foo
<button @click="say">按钮</button>    //hello
----------------------------------------
export default {
  name: 'App',
  setup () {
    let name='foo'  //定义一个常量
    function say() {    //定义一个函数
     console.log('hello')
    }
    return {
      name, //将定义的的常量,函数return出去
      say
    }
  }
}
说明:
1.setup是vue3新的配置项,值为一个函数
2.data,methods,钩子等都配置在里面
3.一般返回一个对象,供模板使用
注意:
1.此时的setup不是响应式的,需要配合ref函数使用
2.尽量不要和vue2的语法混合使用

需要注意的点:

setup执行的时机
    在beforeCreate之前执行一次,this是undefined。
setup的参数
    props:值为对象,包含:组件外部传递过来,且组件内部声明接收了的属性。
    context:上下文对象
        attrs: 相当于vue2中的$attrs
        slots: 收到的插槽内容, 相当于 this.$slots
        emit: 分发自定义事件的函数, 相当于 this.$emit
-----------------------------------------------------------
props:[]    //需要去接收一下,要不然会有警告
setup (props,context) {
    context.attrs
    context.slots
    context.emit
    //setup没有this,只有content
}

2.1.2 ref函数

作用: 定义一个响应式的数据
语法: let xxx = ref(initValue) //initValue为初始值
<h1>{{name}}</h1>
<h1>{{person.sex}}</h1>
<h1>{{person.age}}</h1>
<button @click="changeName">按钮</button>
-------------------------
import {ref} from 'vue'
setup () {
    let name=ref('foo') //处理基本数据类型
    let person=ref({    //处理对象数据类型
      name:'foo',
      age:18
    })
    function changeName() {
      name.value='bar'
      person.value.sex='男'
      person.value.age=20
    }
    return {
      name,
      person,
      changeName
    }
  }
说明:
1.ref可以接收基本类型、对象类型
2.js中需要通过.value来取值,template中直接取值
注意:
ref虽然可以接收对象类型,但是尽量不使用,对象类型最好使用reactive函数

2.1.3 reactive函数

作用: 定义一个对象类型
let xxx= reactive(initValue)    //initValue为初始值
<h1>{{name}}</h1>
<h1>{{person.name}}</h1>
<h1>{{person.age}}</h1>
<h1>{{arr}}</h1>
<button @click="changeName">按钮</button>
--------------------------------------
setup () {
    // let name=reactive('foo') 警告,不能定义基本数据类型
    let person=reactive({
        name:'foo',
        age:18
    })
    let arr=reactive(['1','2','3'])
    function changeName() {
        person.name='bar'
        person.age=20
        arr[0]='4'  //可以直接通过索引操作数据,在vue2中这是行不通的(底层原理不一样)
    }
    return {
      arr,
      person,
     changeName
    }
  }
说明:
1.reactive只接收对象数据类型
2.js和template中直接取值

3.1 Vue3.0中的响应式原理

3.1.1 vue2.x的响应式

实现原理:

对象类型:通过Object.defineProperty()对属性的读取、修改进行拦截(数据劫持)。

数组类型:通过重写更新数组的一系列方法来实现拦截。(对数组的变更方法进行了包裹)。

存在问题:

新增属性、删除属性, 界面不会更新。

直接通过下标修改数组, 界面不会自动更新。

Object.defineProperty(data, 'count', {
    get () {}, 
    set () {}
})

3.1.2 Vue3.0的响应式

实现原理:

通过Proxy(代理): 拦截对象中任意属性的变化, 包括:属性值的读写、属性的添加、属性的删除等。

通过Reflect(反射): 对源对象的属性进行操作。

new Proxy(data, {
    // 拦截读取属性值
    get (target, prop) {
        return Reflect.get(target, prop)
    },
    // 拦截设置属性值或添加新属性
    set (target, prop, value) {
        return Reflect.set(target, prop, value)
    },
    // 拦截删除属性
    deleteProperty (target, prop) {
        return Reflect.deleteProperty(target, prop)
    }
})

4.1 计算属性与监视

4.1.1 computed函数

import {computed} from 'vue'
setup(){
    //计算属性——简写
    let fullName = computed(()=>{
        return person.firstName + '-' + person.lastName
    })
    //计算属性——完整
    let fullName = computed({
        get(){
            return person.firstName + '-' + person.lastName
        },
        set(value){
            const nameArr = value.split('-')
            person.firstName = nameArr[0]
            person.lastName = nameArr[1]
        }
    })
}

4.1.2 watch函数

两个小“坑”:

监视reactive定义的响应式数据时:oldValue无法正确获取、强制开启了深度监视(deep配置失效)。

监视reactive定义的响应式数据中某个属性(对象)时:deep配置有效,oldValue无法正确获取。

let sum=reactive(0)
let msg=reactive('msg')
let person=reactive({
      name:'foo',
      age:18,
      job:{
       s:20
      }
})
//情况一:监视ref定义的响应式数据
watch(sum,(newValue,oldValue)=>{
    console.log('sum变化了',newValue,oldValue)
},{immediate:true})
​
//情况二:监视多个ref定义的响应式数据
watch([sum,msg],(newValue,oldValue)=>{
    console.log('sum或msg变化了',newValue,oldValue)
}) 
​
/* 情况三:监视reactive定义的响应式数据
            若watch监视的是reactive定义的响应式数据,则无法正确获得oldValue!!
            若watch监视的是reactive定义的响应式数据,则强制开启了深度监视 
*/
watch(person,(newValue,oldValue)=>{
    console.log('person变化了',newValue,oldValue)
},{immediate:true,deep:false}) //此处的deep配置不再奏效//情况四:监视reactive定义的响应式数据中的某个属性
watch(()=>person.job,(newValue,oldValue)=>{
    console.log('person的job变化了',newValue,oldValue)
},{immediate:true,deep:true}) 
​
//情况五:监视reactive定义的响应式数据中的某些属性
watch([()=>person.job,()=>person.name],(newValue,oldValue)=>{
    console.log('person的job变化了',newValue,oldValue)
},{immediate:true,deep:true})
​
//特殊情况
watch(()=>person.job,(newValue,oldValue)=>{
    console.log('person的job变化了',newValue,oldValue)
},{deep:true}) //此处由于监视的是reactive素定义的对象中的某个属性,所以deep配置有效

3.watchEffect函数

//watchEffect所指定的回调中用到的数据只要发生变化,则直接重新执行回调。如果没有数据,则初始化执行一次
let name=reactive('foo')
​
watchEffect(()=>{
    const x1 = name.value
    const x2 = person.age
    console.log('watchEffect配置的回调执行了')
})

5.1 生命周期

5.1.1 钩子变化

beforeDestroy 改名为 beforeUnmount
destroyed 改名为 unmounted

5.1.2 写法

配置项的写法

setup () {},
beforeCreate() {}
created() {}
...

组合式写法

//就是在配置项的写法加on,但是却没有beforeCreate,created这2个钩子,setup相当于这2个,直接在里面写就行
import {onBeforeMount} from 'vue'
setup () {
    //onBeforeCreate(()=>{}),onCreated(()=>{})   错误写法,就没有设计这2个钩子
    onBeforeMount(()=>{})
    onMounted(()=>{})
    ....
},

6.1 toRef、toRefs

作用:创建一个 ref 对象,其value值指向另一个对象中的某个属性(方便模板中使用)
语法:
toRef
    const name = toRef(obj,'obj.key')   //第一个参数:要响应的对象,第二个参数:对象的属性
toRefs
    const name = toRef(obj) //参数:要响应的对象

toRef实例

 <h1>{{name}}</h1>
 <h1>{{s}}</h1>
----------------------------
import {reactive,toRef} from 'vue'
setup () {
    let person=reactive({
          name:'foo',
          job:{
           s:20
          }
        })
    return {
      name:toRef(person,'name'),
      s:toRef(person.job,'s'),
    }
}

toRefs实例

 <h1>{{name}}</h1>
 <h1>{{obj.s}}</h1> //只能取到obj,需要s的话,要用obj.s
----------------------------
import {reactive,toRefs} from 'vue'
setup () {
    let person=reactive({
          name:'foo',
          job:{
           s:20
          }
        })
    return {
      ...toRefs(person)     //通过扩展运算符将对象的属性取出,但是只能取一层,
    }
}

7.1 其它 Composition API

7.1.1 shallowReactive 与 shallowRef

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

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

使用:

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

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

7.1.2 readonly 与 shallowReadonly

readonly: 让一个响应式数据变为只读的(深只读)。

shallowReadonly:让一个响应式数据变为只读的(浅只读)。

应用场景: 不希望数据被修改时。

7.1.3 toRaw 与 markRaw

toRaw:

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

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

markRaw:

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

应用场景:

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

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

7.1.4 customRef

作用:创建一个自定义的 ref,并对其依赖项跟踪和更新触发进行显式控制。

<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>

7.1.5 provide 与 inject

作用:实现祖与后代组件间通信

应用:父组件有一个 provide 选项来提供数据,后代组件有一个 inject 选项来开始使用这些数据

祖组件中:

setup(){
    ......
    let person = reactive({name:'foo',age:18})
    provide('p',person)
    ......
}

后代组件中:

setup(){
    ......
    const car = inject('p')
    return {car}
    ......
}

7.1.6 响应式数据的判断

isRef: 检查一个值是否为一个 ref 对象
isReactive: 检查一个对象是否是由 reactive 创建的响应式代理
isReadonly: 检查一个对象是否是由 readonly 创建的只读代理
​
isProxy: 检查一个对象是否是由 reactive 或者 readonly 方法创建的代理

8.1 新的组件

8.1.1 Teleport

//Teleport 是一种能够将我们的组件html结构移动到指定位置的技术。
<teleport to="body">    //移动的位置  可以是html,body等
    <h1>hello</h1>
</teleport>

8.1.2 Suspense

//Suspense:异步组件
//引入
import {defineAsyncComponent} from 'vue'
const Child = defineAsyncComponent(()=>import('./components/Child.vue'))
使用Suspense包裹组件,并配置好default 与 fallback
<template>
    <div class="app">
        <h3>我是App组件</h3>
        <Suspense>
            <template v-slot:default>   //要展示的组件
                <Child/>
            </template>
            <template v-slot:fallback>  //替补组件
                <h3>加载中.....</h3>
            </template>
        </Suspense>
    </div>
</template>

9.1 其他

9.1.1 全局API的转移

Vue3.0中对这些API做出了调整:将全局的API,即:Vue.xxx调整到应用实例(app)上

2.x 全局 API(Vue3.x 实例 API (app)
Vue.config.xxxxapp.config.xxxx
Vue.config.productionTip移除
Vue.componentapp.component
Vue.directiveapp.directive
Vue.mixinapp.mixin
Vue.useapp.use
Vue.prototypeapp.config.globalProperties

9.1. 2 其他改变

1. data选项应始终被声明为一个函数。
2. 过度类名的更改  .v-enter==>.v-enter-from,.v-leave==>.v-leave-from
3. 移除keyCode作为 v-on 的修饰符,同时也不再支持config.keyCodes
4. 移除修饰符
    //父组件
    <my-component
      v-on:close="handleComponentEvent"
      v-on:click="handleNativeClickEvent"
    />
    //子组件
    ------------------
    <script>
      export default {
        emits: ['close']    //close是自定义组件,click没有写,默认为原生 (v-on.native)
      }
    </script>
5. 移除过滤器(filter)

如果觉得有帮助欢迎点赞、评论。 上述内容仅仅代表个人观点,如有错误,请指正。如果你也对前端感兴趣,欢迎访问我的个人博客sundestiny.github.io/myblog/