让你30分钟快速掌握vue3教程

经过了漫长的迭代,Vue 3.0终于在上2020-09-18发布了,带了翻天覆地的变化,使用了Typescript 进行了大规模的重构,带来了Composition API RFC版本,类似React Hook 一样的写Vue,可以自定义自己的hook ,让使用者更加的灵活,接下来总结一下vue 3.0 带来的部分新特性。

  • setup()
  • ref()
  • reactive()
  • isRef()
  • toRefs()
  • computed()
  • watch()
  • LifeCycle Hooks(新的生命周期)
  • Template refs
  • globalProperties
  • Suspense

Vue2与Vue3的对比

  • 对TypeScript支持不友好(所有属性都放在了this对象上,难以推倒组件的数据类型)
  • 大量的API挂载在Vue对象的原型上,难以实现TreeShaking。
  • 架构层面对跨平台dom渲染开发支持不友好
  • CompositionAPI。受ReactHook启发
  • 更方便的支持了 jsx
  • Vue 3 的 Template 支持多个根标签,Vue 2 不支持
  • 对虚拟DOM进行了重写、对模板的编译进行了优化操作...

一、setup 函数

setup() 函数是 vue3 中,专门为组件提供的新属性。它为我们使用 vue3 的 Composition API 新特性提供了统一的入口, setup 函数会在 beforeCreate 之后、created 之前执行, vue3也是取消了这两个钩子,统一用setup代替, 该函数相当于一个生命周期函数,vue中过去的data,methods,watch等全部都用对应的新增api写在setup()函数中

setup(props, context) {
  context.attrs
  context.slots
  context.parent
  context.root
  context.emit
  context.refs

  return {

  }
 }
  • props: 用来接收 props 数据
  • context 用来定义上下文, 上下文对象中包含了一些有用的属性,这些属性在 vue 2.x 中需要通过 this 才能访问到, 在 setup() 函数中无法访问到 this,是个 undefined
  • 返回值: return {}, 返回响应式数据, 模版中需要使用的函数

二、reactive 函数

reactive() 函数接收一个普通对象,返回一个响应式的数据对象, 想要使用创建的响应式数据也很简单,创建出来之后,在setup中return出去,直接在template中调用即可

<template>
 {{name}} // test
<template>

<script lang="ts">
import { defineComponent, reactive, ref, toRefs } from 'vue';
export default defineComponent({
 setup(props, context) {

  let state = reactive({
   name: 'test'
  });

  return state
 }
});
</script>

三、ref() 函数

ref() 函数用来根据给定的值创建一个响应式的数据对象,ref() 函数调用的返回值是一个对象,这个对象上只包含一个 value 属性, 只在setup函数内部访问ref函数需要加.value

<template>
  <div class="mine">
    {{count}} // 10
  </div>
</template>

<script lang="ts">
import { defineComponent, ref } from 'vue';
export default defineComponent({
 setup() {
  const count = ref<number>(10)
  // 在js 中获取ref 中定义的值, 需要通过value属性
  console.log(count.value);
  return {
    count
  }
  }
});
</script>

在 reactive 对象中访问 ref 创建的响应式数据

<template>
  <div class="mine">
    {{count}} -{{t}} // 10 -100
  </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, toRefs } from 'vue';
export default defineComponent({
 setup() {
  const count = ref<number>(10)
  const obj = reactive({
   t: 100,
   count
  })
  // 通过reactive 来获取ref 的值时,不需要使用.value属性
  console.log(obj.count);
  return {
    ...toRefs(obj)
  }
  }
});
</script>

四、isRef() 函数

isRef() 用来判断某个值是否为 ref() 创建出来的对象

<script lang="ts">
import { defineComponent, isRef, ref } from 'vue';
export default defineComponent({
 setup(props, context) {
  const name: string = 'vue'
  const age = ref<number>(18)
  console.log(isRef(age)); // true
  console.log(isRef(name)); // false

  return {
   age,
   name
  }
 }
});
</script>

五、toRefs() 函数

toRefs() 函数可以将 reactive() 创建出来的响应式对象,转换为普通的对象,只不过,这个对象上的每个属性节点,都是 ref() 类型的响应式数据

<template>
 <div class="mine">
  {{name}} // test
  {{age}} // 18
 </div>
</template>

<script lang="ts">
import { defineComponent, reactive, ref, toRefs } from 'vue';
export default defineComponent({
 setup(props, context) {
  let state = reactive({
   name: 'test'
  });

  const age = ref(18)

  return {
   ...toRefs(state),
   age
  }
 }
});
</script>

六、computed()

该函数用来创造计算属性,和过去一样,它返回的值是一个ref对象。 里面可以传方法,或者一个对象,对象中包含set()、get()方法

6.1 创建只读的计算属性

import { computed, defineComponent, ref } from 'vue';
export default defineComponent({
 setup(props, context) {
  const age = ref(18)

  // 根据 age 的值,创建一个响应式的计算属性 readOnlyAge,它会根据依赖的 ref 自动计算并返回一个新的 ref
  const readOnlyAge = computed(() => age.value++) // 19

  return {
   age,
   readOnlyAge
  }
 }
});
</script>

6.2 通过set()、get()方法创建一个可读可写的计算属性

<script lang="ts">
import { computed, defineComponent, ref } from 'vue';
export default defineComponent({
 setup(props, context) {
  const age = ref<number>(18)

  const computedAge = computed({
   get: () => age.value + 1,
   set: value => age.value + value
  })
  // 为计算属性赋值的操作,会触发 set 函数, 触发 set 函数后,age 的值会被更新
  age.value = 100
  return {
   age,
   computedAge
  }
 }
});
</script>

七、 watch() 函数

watch 函数用来侦听特定的数据源,并在回调函数中执行副作用。默认情况是懒执行的,也就是说仅在侦听的源数据变更时才执行回调。

7.1 监听用reactive声明的数据源

<script lang="ts">
import { computed, defineComponent, reactive, toRefs, watch } from 'vue';
interface Person {
 name: string,
 age: number
}
export default defineComponent({
 setup(props, context) {
  const state = reactive<Person>({ name: 'vue', age: 10 })

  watch(
   () => state.age,
   (age, preAge) => {
    console.log(age); // 100
    console.log(preAge); // 10
   }
  )
  // 修改age 时会触发watch 的回调, 打印变更前后的值
  state.age = 100
  return {
   ...toRefs(state)
  }
 }
});
</script>

7.2 监听用ref声明的数据源

<script lang="ts">
import { defineComponent, ref, watch } from 'vue';
interface Person {
 name: string,
 age: number
}
export default defineComponent({
 setup(props, context) {
  const age = ref<number>(10);

  watch(age, () => console.log(age.value)); // 100

  // 修改age 时会触发watch 的回调, 打印变更后的值
  age.value = 100
  return {
   age
  }
 }
});
</script>

7.3 同时监听多个值

<script lang="ts">
import { computed, defineComponent, reactive, toRefs, watch } from 'vue';
interface Person {
 name: string,
 age: number
}
export default defineComponent({
 setup(props, context) {
  const state = reactive<Person>({ name: 'vue', age: 10 })

  watch(
   [() => state.age, () => state.name],
   ([newName, newAge], [oldName, oldAge]) => {
    console.log(newName);
    console.log(newAge);

    console.log(oldName);
    console.log(oldAge);
   }
  )
  // 修改age 时会触发watch 的回调, 打印变更前后的值, 此时需要注意, 更改其中一个值, 都会执行watch的回调
  state.age = 100
  state.name = 'vue3'
  return {
   ...toRefs(state)
  }
 }
});
</script>

7.4 stop 停止监听

在 setup() 函数内创建的 watch 监视,会在当前组件被销毁的时候自动停止。如果想要明确地停止某个监视,可以调用 watch() 函数的返回值即可,语法如下:

<script lang="ts">
import { set } from 'lodash';
import { computed, defineComponent, reactive, toRefs, watch } from 'vue';
interface Person {
 name: string,
 age: number
}
export default defineComponent({
 setup(props, context) {
  const state = reactive<Person>({ name: 'vue', age: 10 })

  const stop = watch(
   [() => state.age, () => state.name],
   ([newName, newAge], [oldName, oldAge]) => {
    console.log(newName);
    console.log(newAge);

    console.log(oldName);
    console.log(oldAge);
   }
  )
  // 修改age 时会触发watch 的回调, 打印变更前后的值, 此时需要注意, 更改其中一个值, 都会执行watch的回调
  state.age = 100
  state.name = 'vue3'

  setTimeout(()=> {
   stop()
   // 此时修改时, 不会触发watch 回调
   state.age = 1000
   state.name = 'vue3-'
  }, 1000) // 1秒之后讲取消watch的监听

  return {
   ...toRefs(state)
  }
 }
});
</script>

八、LifeCycle Hooks(新的生命后期)

新版的生命周期函数,可以按需导入到组件中,且只能在 setup() 函数中使用, 但是也可以在setup 外定义, 在 setup 中使用

<script lang="ts">
import { set } from 'lodash';
import { defineComponent, onBeforeMount, onBeforeUnmount, onBeforeUpdate, onErrorCaptured, onMounted, onUnmounted, onUpdated } from 'vue';
export default defineComponent({
 setup(props, context) {
  onBeforeMount(()=> {
   console.log('beformounted!')
  })
  onMounted(() => {
   console.log('mounted!')
  })

  onBeforeUpdate(()=> {
   console.log('beforupdated!')
  })
  onUpdated(() => {
   console.log('updated!')
  })

  onBeforeUnmount(()=> {
   console.log('beforunmounted!')
  })
  onUnmounted(() => {
   console.log('unmounted!')
  })

  onErrorCaptured(()=> {
   console.log('errorCaptured!')
  })

  return {}
 }
});
</script>

九、Template refs

通过refs 来回去真实dom元素, 这个和react 的用法一样,为了获得对模板内元素或组件实例的引用,我们可以像往常一样在setup()中声明一个ref并返回它

  • 还是跟往常一样,在 html 中写入 ref 的名称
  • 在steup 中定义一个 ref
  • steup 中返回 ref的实例
  • onMounted 中可以得到 ref的RefImpl的对象, 通过.value 获取真实dom
<template>
 <!--第一步:还是跟往常一样,在 html 中写入 ref 的名称-->
 <div class="mine" ref="elmRefs">
  <span>1111</span>
 </div>
</template>

<script lang="ts">
import { set } from 'lodash';
import { defineComponent, onMounted, ref } from 'vue';
export default defineComponent({
 setup(props, context) {
  // 获取真实dom
  const elmRefs = ref<null | HTMLElement>(null);
  onMounted (() => {
   console.log(elmRefs.value); // 得到一个 RefImpl 的对象, 通过 .value 访问到数据
  })

  return {
   elmRefs
  }
 }
});
</script>

十、vue 的全局配置

通过vue 实例上config来配置,包含Vue应用程序全局配置的对象。您可以在挂载应用程序之前修改下面列出的属性:

const app = Vue.createApp({})

app.config = {...}

为组件渲染功能和观察程序期间的未捕获错误分配处理程序。错误和应用程序实例将调用处理程序

app.config.errorHandler = (err, vm, info) => {}

可以在应用程序内的任何组件实例中访问的全局属性,组件的属性将具有优先权。这可以代替Vue 2.xVue.prototype扩展:

const app = Vue.createApp({})

app.config.globalProperties.$http = 'xxxxxxxxs'

可以在组件用通过 getCurrentInstance() 来获取全局globalProperties 中配置的信息,getCurrentInstance 方法获取当前组件的实例,然后通过 ctx 属性获得当前上下文,这样我们就能在setup中使用router和vuex, 通过这个属性我们就可以操作变量、全局属性、组件属性等等

setup( ) {
 const { ctx } = getCurrentInstance();
 ctx.$http
}

十一、Suspense 组件

在开始介绍 Vue 的 Suspense 组件之前,我们有必要先了解一下 React 的 Suspense 组件,因为他们的功能类似。

React.lazy 接受一个函数,这个函数需要动态调用 import()。它必须返回一个 Promise,该 Promise 需要 resolve 一个 default export 的 React 组件。

import React, { Suspense } from 'react';

const myComponent = React.lazy(() => import('./Component'));

function MyComponent() {
 return (
  <div>
   <Suspense fallback={<div>Loading...</div>}>
    <myComponent />
   </Suspense>
  </div>
 );
}

Vue3 也新增了 React.lazy 类似功能的 defineAsyncComponent 函数,处理动态引入(的组件)。defineAsyncComponent可以接受返回承诺的工厂函数。当您从服务器检索到组件定义时,应该调用Promise的解析回调。您还可以调用reject(reason)来指示负载已经失败

import { defineAsyncComponent } from 'vue'

const AsyncComp = defineAsyncComponent(() =>
 import('./components/AsyncComponent.vue')
)

app.component('async-component', AsyncComp)

Vue3 也新增了 Suspense 组件:

<template>
 <Suspense>
  <template #default>
   <my-component />
  </template>
  <template #fallback>
   Loading ...
  </template>
 </Suspense>
</template>

<script lang='ts'>
 import { defineComponent, defineAsyncComponent } from "vue";
 const MyComponent = defineAsyncComponent(() => import('./Component'));

export default defineComponent({
  components: {
   MyComponent
  },
  setup() {
   return {}
  }
})

</script>

十二、vue 3.x 完整组件模版结构

一个完成的vue 3.x 完整组件模版结构包含了:组件名称、 props、components、setup(hooks、computed、watch、methods 等)

<template>
 <div class="mine" ref="elmRefs">
  <span>{{name}}</span>
  <br>
  <span>{{count}}</span>
  <div>
   <button @click="handleClick">测试按钮</button>
  </div>

  <ul>
   <li v-for="item in list" :key="item.id">{{item.name}}</li>
  </ul>
 </div>
</template>

<script lang="ts">
import { computed, defineComponent, getCurrentInstance, onMounted, PropType, reactive, ref, toRefs } from 'vue';

interface IState {
 count: 0,
 name: string,
 list: Array<object>
}

export default defineComponent({
 name: 'demo',
 // 父组件传子组件参数
 props: {
  name: {
   type: String as PropType<null | ''>,
   default: 'vue3.x'
  },
  list: {
   type: Array as PropType<object[]>,
   default: () => []
  }
 },
 components: {
  /// TODO 组件注册
 },
 emits: ["emits-name"], // 为了提示作用
 setup (props, context) {
  console.log(props.name)
  console.log(props.list)

  const state = reactive<IState>({
   name: 'vue 3.0 组件',
   count: 0,
   list: [
    {
     name: 'vue',
     id: 1
    },
    {
     name: 'vuex',
     id: 2
    }
   ]
  })

  const a = computed(() => state.name)

  onMounted(() => {

  })

  function handleClick () {
   state.count ++
   // 调用父组件的方法
   context.emit('emits-name', state.count)
  }

  return {
   ...toRefs(state),
   handleClick
  }
 }
});
</script>

vue 3 的生态

UI 组件库

vant2.x

Ant Design of Vue 2.x

element-plus

到此这篇关于让你30分钟快速掌握vue3教程的文章就介绍到这了,更多相关vue3 入门内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • vue3.0 CLI - 1 - npm 安装与初始化的入门教程

    node 开发环境请先自行准备 npm install -g @vue/cli 安装完成之后命令行则存在 vue 命令 vue -V 查看本地 vue 版本 vue -h 输出帮助 vue create <project-name> 进入工程文件夹,创建项目. 如:cd studyVue ( 进入工程文件夹 ) vue create config ( 创建 config 项目 ) 选择 default 配置项,下面没什么可介绍的,自行尝试. 下面介绍选择 manually select fea

  • 详解Vue3.0 前的 TypeScript 最佳入门实践

    前言 我个人对更严格类型限制没有积极的看法,毕竟各类转类型的骚写法写习惯了. 然鹅最近的一个项目中,是 TypeScript + Vue ,毛计喇,学之...-真香! 注意此篇标题的"前",本文旨在讲Ts混入框架的使用,不讲Class API 1. 使用官方脚手架构建 npm install -g @vue/cli # OR yarn global add @vue/cli 新的 Vue CLI 工具允许开发者 使用 TypeScript 集成环境 创建新项目. 只需运行 vue cr

  • vue3.0 CLI - 2.1 - component 组件入门教程

    我的 github 地址 - vue3.0Study - 阶段学习成果都会建立分支. 进入 src 文件夹,这是实际都工程文件夹,其他文件夹以及文件以后在了解. 3个文件夹  assets - 各类静态资源文件夹 - 比如 图片, css 文件等.  components - 组件文件夹, 组件是 vue 等 MVC 框架等核心概念,自行了解含义. view - 视图文件夹. 5个文件  app.vue.main.js - 主视图.配合 main.js 成为 vue 程序的主入口.router.

  • vue3.0 CLI - 2.6 - 组件的复用入门教程

    我的 github 地址 - vue3.0Study- 阶段学习成果都会建立分支. ========================== 定义一个基础组件 这个基础组件,是导航条中 可以复用 的基础组件 单个导航. 基础组件[导航组件]基础的功能是能够显示文字,单击的交互方式.明确任务目标之后,进行开发. 在 component 目录下新建 Base 目录,Base 下新建文件 TopNav.vue.加入如下代码: <template> <div class="topnav&q

  • 让你30分钟快速掌握vue3教程

    经过了漫长的迭代,Vue 3.0终于在上2020-09-18发布了,带了翻天覆地的变化,使用了Typescript 进行了大规模的重构,带来了Composition API RFC版本,类似React Hook 一样的写Vue,可以自定义自己的hook ,让使用者更加的灵活,接下来总结一下vue 3.0 带来的部分新特性. setup() ref() reactive() isRef() toRefs() computed() watch() LifeCycle Hooks(新的生命周期) Te

  • 30分钟快速入门掌握ES6/ES2015的核心内容(下)

    前言 在 30分钟掌握ES6/ES2015核心内容(上)我们讲解了es6最常用的一些语法:let, const, class, extends, super, arrow functions, template string, destructuring, default, rest arguments 俗话说打铁要趁热,今天我们继续讲es6其他几个非常有用的新特性. import export 这两个家伙对应的就是es6自己的module功能. 我们之前写的Javascript一直都没有模块化

  • 反向Ajax 30分钟快速掌握

    场景1:当有新邮件的时候,网页自动弹出提示信息而无需用户手动的刷新收件箱. 场景2:当用户的手机扫描完成页面中的二维码以后,页面会自动跳转. 场景3:在类似聊天室的环境中有任何人发言,所有登录用户都可以即时看见信息. 与传统的MVC模型请求必须从客户端发起由服务器响应相比,使用反向Ajax能够模拟服务器端主动向客户端推送事件从而提高用户体验.本文将分两个部分讨论反向Ajax技术,包括:Comet和WebSocket.文章旨在演示如何实现以上两种技术手段,Struts2或SpringMVC中的应用

  • 30分钟快速入门掌握ES6/ES2015的核心内容(上)

    前言 ECMAScript 6(以下简称ES6)是JavaScript语言的下一代标准.因为当前版本的ES6是在2015年发布的,所以又称ECMAScript 2015. 也就是说,ES6就是ES2015. 虽然目前并不是所有浏览器都能兼容ES6全部特性,但越来越多的程序员在实际项目当中已经开始使用ES6了.所以就算你现在不打算使用ES6,但为了看懂别人的你也该懂点ES6的语法了... 在我们正式讲解ES6语法之前,我们得先了解下Babel. Babel Babel是一个广泛使用的ES6转码器,

  • Fuel 30 分钟快速安装OpenStack(图文教程)

    一直以来,对于openstack 的初学者来讲,安装往往是入门的头大难题.在E版本之前,要搭建一个基本能用的openstack 环境那是相当麻烦,自己要装机,自己搞源,自己照着文档敲命令,又没有靠谱的文档,官方给出的文档依旧有好多坑,还有语言问题往往用上好几天时间都装不起来,慢慢地就丧失了学习openstack 的信心! 不过后来情况有了很大改观,从E版本开始,以后安装过程简化许多,文档质量提高不少.尽管如此对于初学者还讲还是比较复杂,其实很多时候,很多人只是想体会一下openstack,完全不

  • 30分钟快速掌握Bootstrap框架

    什么是 Bootstrap? Bootstrap 是一个用于快速开发 Web 应用程序和网站的前端框架.Bootstrap 是基于 HTML.CSS.JAVASCRIPT 的. 历史 Bootstrap 是由 Twitter 的 Mark Otto 和 Jacob Thornton 开发的.Bootstrap 是 2011 年八月在 GitHub 上发布的开源产品. 最近空余时间比较多,今天先给大家介绍一个前端"样式"框架--Bootstrap. 一.Bootstrap 整体架构 为什

  • 30分钟快速带你理解iOS中的谓词NSPredicate

    一.引言 在现代汉语的解释中,谓词是用来描述或判断客体性质.特征或者客体之间关系的词项.通俗的说,它是描述事物属性的.在iOS开发Cocoa框架中,有提供NSPredicate类,这个类通常也被成为谓词类,其主要的作用是在Cocoa中帮助查询和检索,但是需要注意,实质上谓词并不是提供查询和检索的支持,它是一种描述查询检索条件的方式,就像更加标准通用的正则表达式一样. NSPredicate提供的谓词可以分为两类:比较谓词和复合谓词. 比较谓词:比较谓词通过使用比较运算符来描述所符合条件的属性状态

  • 30分钟快速实现小程序语音识别功能

    前言 为了参加某个作秀活动,研究了一波如何结合小程序.科大讯飞实现语音录入.识别的实现.科大讯飞开发文档中只给出 Python 的 demo,并没有给出 node.js 的 sdk,但问题不大.本文将从小程序相关代码到最后对接科大讯飞 api 过程,一步步介绍,半个小时,搭建完成小程序语音识别功能!不能再多了! 当然,前提是最好掌握有一点点小程序.node.js 甚至是音频相关的知识.下面话不多说了,来一起看看详细的介绍吧 架构先行 架构比较简单,大伙儿可以先看下图.除了小程序,需要提供 3 个

  • 理解AngularJs篇:30分钟快速掌握AngularJs

    一.前言 对于前端系列,自然少不了AngularJs的介绍了.在前面文章中,我们介绍了如何使用KnockoutJs来打造一个单页面程序,后面一篇文章将介绍如何使用AngularJs的开发一个单页面应用程序.在开始使用AngularJs开发SPA之前,我觉得有必要详细介绍下AngularJs所涉及的知识点.所有也就有了这篇文章. 二.AngularJs介绍 AngularJS是Google推出的一款Web应用开发框架.它提供了一系列兼容性良好并可扩展的服务,包括数据绑定.DOM操作.MVC和依赖注

  • HTML 30分钟入门教程

    运行下面的代码就可以了 HTML 30分钟入门教程 h1 {text-align:center} p {text-indent:2em; line-height:140%; margin:auto 10px} span {margin:3px} .code { border:solid 1px gray; background-color:#eee} .name { font-weight:bold } dl {margin-left:20px} dt {font-weight:bold} .t

随机推荐