首页前端开发VUE走进Vue【二】Vue3语法糖

走进Vue【二】Vue3语法糖

时间2023-04-25 03:51:01发布访客分类VUE浏览602
导读:🌟前言随着2020年9月18号Vue3.0的发布,到现在已经有两年半的时间了,再到尤大大官宣从去年的2月7号开始,Vue3.0将成为Vue.js的默认版本。相信很多小伙伴也已经感受到了Vue3的变化和其独特魅力,虽然技术更迭不停,但我们也不...

🌟前言

随着2020年9月18号Vue3.0的发布,到现在已经有两年半的时间了,再到尤大大官宣从去年的2月7号开始,Vue3.0将成为Vue.js的默认版本。相信很多小伙伴也已经感受到了Vue3的变化和其独特魅力,虽然技术更迭不停,但我们也不能停下脚步。今天给小伙伴们整理了一些Vue3里的语法糖,大家可以结合Vue2去仔细感受一下,话不多说,咱直接开整。

🌟组合式API:setup()

组合式API是vue3里边变化比较大的一个点,习惯了Vue2写法,当时突然学习的时候还真得有点不适应
Vue 3 的 Composition API 系列里,推出了一个全新的 setup 函数,它是一个组件选项,在创建组件之前执行,一旦 props 被解析,并作为组合式 API 的入口点。


1、setup函数是处于 生命周期函数 beforeCreate 和 Created 两个钩子函数之间的函数 也就说在 setup函数中是无法 使用 data 和 methods 中的数据和方法的。

2、setup函数是 Composition API(组合API)的入口。

3、在setup函数中定义的变量和方法最后都是需要 return 出去的 不然无法再模板中使用。

 //  setup()写法一:
template>
    
 div id="app">

  {
{
name}
}
    
  p>
{
{
age}
}
    /p>
    
  button @click="plusOne()">
    +/button>
    
 /div>
    
/template>
    

script>

import {
ref}
 from 'vue'
export default {

 name:'app',
 data(){

  return {

   name:'xiaosan'
  }

 }
,
 setup(){

  const name =ref('满山雾')
  const age=ref(18) // 永远18
  function plusOne(){

   age.value++ //想改变值或获取值 必须.value
  }

  return {
 //必须返回 模板中才能使用
   name,age,plusOne
  }

 }

}
    
/script>
    

大家可以看到,通过这种setup写法我们还需要把变量return 出去才能在页面中使用,是不是有点…

别着急,给大家上点小魔法(setup语法糖)

 //  setup()写法二:
template>
    
 div id="app">

  {
{
name}
}
    
  p>
{
{
age}
}
    /p>
    
  button @click="plusOne()">
    +/button>
    
 /div>
    
/template>
    

script setup>

import {
ref}
 from 'vue'
export default {

 name:'app',
 data(){

  return {

   name:'xiaosan'
  }

 }
,

  const name =ref('满山雾')
  const age=ref(18) // 永远18
  function plusOne(){

    age.value++ //想改变值或获取值 必须.value
  }

}
    
/script>
    

当我们再script标签上写了setup以后,就直接可以写我们的代码了,老板再也不用担心我们的变量或者function 忘记 return 了。

*注意:在setup中不能使用this,因为他找不到实例。但是在vue2语法和vue3语法混用的时候,vue2语法中可以使用this访问到setup里暴露出的变量。

1.它只是简化了以往的组合API(compositionApi)的必须返回(return)的写法,并且有更好的运行时性能。

2.在setup函数中所有ES 模块导出都被认为是暴露给上下文的值,并包含在 setup() 返回对象中。相对于之前的写法,使用后,语法也变得更简单。

🌟生命周期





可以看到 Vue 2 生命周期里的 beforeCreate 和 created ,在 Vue 3 里已被 setup 替代。

在Vue3中如果要用到生命周期钩子函数,需要这样:

script setup>

import {
 onMounted }
     from 'vue'

 onMounted(() =>
 {

       console.log('mounted in the composition api!')
     }
    )
/script>
    
 

🌟ref

ref是最常用的一个响应式 API,它可以用来定义所有类型的数据,包括 Node 节点和组件。返回一个响应式对象,所有的值都通过.value属性获取。

template>
    
  div>
{
{
num}
}
    /div>
    
/template>
    
script setup >

import {
 ref }
     from 'vue'
const num = ref(0)  // number
const message= ref('大家好')  // string
/script>
    

🌟reactive

返回一个对象的响应式代理。

1.reactive接受一个对象作为参数
2.其返回值是经reactive函数包装过后的数据对象,这个对象具有响应式

template>
    
  div>
{
{
state.searchInfo.name}
}
    /div>
    
/template>
    
script setup >

import {
 reactive }
 from 'vue'

const state = reactive({

  searchInfo: {

    name: 'Jack',
  }
,
}
    )
/script>
    

🌟组件自动注册

在setup中不再需要用过components进行注册,直接引入即可使用。

template>
    
 Son/>
    
/template>
    

script setup>
    
import Son from '@/components/Son.vue'
/script>
    

🌟defineProps

接收父组件传过来的内容,可以定义类型和默认值

template>
    
  div class="hello">
    
  我是父组件
  !-- 父组件通过:变量(这里是info)绑定值 -->
    
   Child :info="parentMsg">
    /Child>
    
  /div>
    
/template>
    
 
script setup>

import Child from './Child'
import {
ref}
     from 'vue'
const parentMsg=ref('父组件传递值是a')
 
/script>
    
 
style scoped>
    
 
/style>
    
template>
    
!-- info是父组件传递过了的值 -->
    
  div>
我是子组件拿到了父组件的值是{
{
info}
}
    /div>
    
/template>
    
 
script setup>

import {
 toRefs, defineProps }
 from 'vue'
const props = defineProps({

  //子组件接收父组件传递过来的值
  info: String,
}
)
//使用父组件传递过来的值
const {
info}
     =toRefs(props)
 
/script>
    
 
style>
    
 
/style>
    

🌟defineEmit

Vue2 中子组件数据传递到父组件,通常是使用 $emit 触发一个自定义事件来进行传递。但在Vue3中 $emit 无法在 script setup > 中使用,这时候我们需要使用 defineEmits():

!-- 子组件 -->
    
script setup>

const emit = defineEmits(['someEvent'])
function onClick() {

  emit('someEvent', 'child message')
}
    
/script>
    
 
template>
    
  button @click="onClick">
    点击/button>
    
/template>
    
!-- 父组件 -->
    
script setup>

import ChildView from './ChildView.vue'
 
function someEvent(value) {

  console.log(value) // child message
}
    
/script>
    
 
template>
    
  ChildView @some-event="someEvent" />
    
/template>
    

🌟defineExpose

向外暴露组件内方法和属性。

传统的写法,我们可以在父组件中,通过 ref 实例的方式去访问子组件的内容,但在 script setup 中,该方法就不能用了,setup 相当于是一个闭包,除了内部的 template 模板,谁都不能访问内部的数据和方法。

// 子组件
const table = ref(null)
defineExpose({

  table,
}
    )
// 父组件
template>
    
 Child ref="child" />
    
/template>
    

script setup>

import {
 ref, onMounted }
     from 'vue'
import Child from './Child.vue'

let child = ref(null);
    

onMounted(() =>
 {
    
 console.log(child.value.table);
 // Child Components
}
    )
/script>
    

🌟watch 和 watchEffect

watch(
  source, // 必传,要侦听的数据源
  callback // 必传,侦听到变化后要执行的回调函数
  // options // 可选,一些侦听选项
)
template>
    
  div>
{
{
num}
}
    /div>
    
/template>
    
script setup >

import {
 watchEffect, watch, ref }
     from 'vue'

const num = ref(1)

var id = setInterval(() =>
 {

  num.value = num.value + 1
  if (num.value === 20) {

    clearInterval(id)
    id = null
  }

}
    , 1000)

watchEffect(() =>
 {

  console.log(1111)
}
    )

watch(() =>
     num.value, () =>
 {

  console.log(222, num.value)
}
    )
/script>
    

watch和watchEffect区别:
1、watch是惰性执行,也就是只有监听的值发生变化的时候才会执行,但是watchEffect不同,每次代码加载watchEffect都会执行(忽略watch第三个参数的配置,如果修改配置项也可以实现立即执行)

2、watch需要传递监听的对象,watchEffect不需要

3、watch只能监听响应式数据:ref定义的属性和reactive定义的对象,如果直接监听reactive定义对象中的属性是不允许的,除非使用函数转换一下

4、watchEffect如果监听reactive定义的对象是不起作用的,只能监听对象中的属性。

🌟useSlots() 和 useAttrs()

获取插槽数据和获取attrs数据,里面包含了 class、属性、方法。

// 旧
script setup>

  import {
 useContext }
 from 'vue'

  const {
 slots, attrs }
     = useContext()
/script>
    

// 新
script setup>

  import {
 useAttrs, useSlots }
     from 'vue'

  const attrs = useAttrs()
  const slots = useSlots()
/script>
    

🌟VueUse

在给大家推介一个非常好用的vue3工具–VueUse

什么是 VueUse VueUse不是Vue.use,它是为Vue 2和3服务的一套Vue Composition API的常用工具集,是目前世界上Star最高的同类型库之一。它的初衷就是将一切原本并不支持响应式的JS
API变得支持响应式,省去程序员自己写相关代码

VueUse 是一个基于 Composition API
的实用函数集合。通俗的来说,这就是一个工具函数包支持了更好的逻辑分离,它可以帮助你快速实现一些常见的功能,免得你自己去写,解决重复的工作内容。以及进行了机遇
Composition API 的封装。

VueUse官网

VueUse安装

npm i @vueuse/core

VueUse使用

// 导入
import {
 useMouse, usePreferredDark, useLocalStorage }
 from "@vueuse/core"

export default {

  setup() {

    // tracks mouse position
    const {
 x, y }
 = useMouse()

    // is user prefers dark theme
    const isDark = usePreferredDark()

    // persist state in localStorage
    const store = useLocalStorage(
      "my-storage",
      {

        name: "Apple",
        color: "red",
      }
,
    )

    return {
 x, y, isDark, store }

  }

}
    

上面从 VueUse 当中导入了三个函数, useMouse, usePreferredDark, useLocalStorage。useMouse 是一个监听当前鼠标坐标的一个方法,他会实时的获取鼠标的当前的位置。usePreferredDark 是一个判断用户是否喜欢深色的方法,他会实时的判断用户是否喜欢深色的主题。useLocalStorage 是一个用来持久化数据的方法,他会把数据持久化到本地存储中。

还有我们熟悉的 防抖 和 节流

import {
 throttleFilter, debounceFilter, useLocalStorage, useMouse }
 from "@vueuse/core"

// 以节流的方式去改变 localStorage 的值
const storage = useLocalStorage("my-key", {
 foo: "bar" }
, {
 eventFilter: throttleFilter(1000) }
)

// 100ms后更新鼠标的位置
const {
 x, y }
 = useMouse({
 eventFilter: debounceFilter(100) }
    )

更多玩法大家可以去VueUse官方网站去进行摸索哦

🌟写在最后

这篇文章为大家介绍了Vue3当中的一些语法糖还有一个200+功能的Vue3工具,你是否学会了呢,小伙伴一定记的尝试哦,后续会为小伙伴们持续更新Vue的一些实战小魔法!各位小伙伴让我们 let’s be prepared at all times!



声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!

存储JavaScript程序员API

若转载请注明出处: 走进Vue【二】Vue3语法糖
本文地址: https://pptw.com/jishu/7925.html
vue 攻防演练|RASP让WebShell攻击破防了

游客 回复需填写必要信息