Vue3之script-setup 语法糖

简介: 本文介绍了Vue 3的`<script setup>`语法糖,通过示例代码演示了如何在组件中使用`<script setup>`以及相关的Vue 3 Composition API函数和特性,如响应式引用、生命周期钩子、CSS模块等,并展示了组件间的通信和样式应用。

前言

简单了解和记录一下Vue3常用的语法使用方式,颇有收益~

传送门:Vue.js - 渐进式 JavaScript 框架 | Vue.js

一、示例代码

(1)/src/views/Example/ScriptSetup/index.vue

<template>
  <div id="v-root" class="v-root" ref="vRootRef">
    <div class="v-root-main">
      <h1 :class="$vRootStyle.title">ROOT父组件</h1>

      <v-child id="v-child" class="v-child" ref="vChildRef" :username="username" @handleFromVChildClick="handleFromVChildClick">

        <div style="background-color: #ffa; text-align: center; font-size: 14px">匿名插槽</div>

        <template v-slot:sign>
          <div style="background-color: #faf; text-align: center; font-size: 14px">具名插槽(sign)</div>
        </template>
      </v-child>

      <div class="operation">
        <el-button size="small" type="primary" @click="handleGetSkillsClick($event)">
          <el-icon :size="18"><Check /></el-icon>
          <span>点击获取子组件暴露的指定属性</span>
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import {
   
    onMounted, ref, getCurrentInstance, toRaw, useCssModule, provide } from 'vue'
import vChild from './vChild'

let username = ref('帅龍之龍') // 响应式数据声明,建议基本数据类型

const handleFromVChildClick = (e) => {
   
   
  console.log('handleFromVChildClick =>', e)
}

const vChildRef = ref(null)
const handleGetSkillsClick = (e) => {
   
   
  console.log('vChildRef.value =>', vChildRef.value)
  console.log('vChildRef.value.age =>', vChildRef.value.age)
  console.log('vChildRef.value.skills =>', vChildRef.value.skills)
  vChildRef.value.fn('OK')
}

const currentInstance = getCurrentInstance() // 在Vue2中,可通过this来获取当前组件实例,在Vue3中,可通过getCurrentInstance()来获取当前组件实例
const {
   
    ctx } = getCurrentInstance() // ctx 相当于Vue2的this,仅作用于开发阶段
const {
   
    proxy } = getCurrentInstance() // proxy 相当于Vue2的this,仅作用于生产阶段
console.log('currentInstance =>', currentInstance)
console.log('ctx =>', ctx)
console.log('proxy =>', proxy)

onMounted(() => {
   
   
  document.title = 'Vue3之script-setup 语法糖'

  const refs = currentInstance.refs
  console.log('refs =>', refs)
  console.log('vRootRef =>', refs.vRootRef)
  console.log('vChildRef =>', refs.vChildRef)
  console.log('vChildDom =>', document.getElementById('v-child'))
})

// 通过 useCssModule 和 <style moudle> 标签对生成的CSS类名做 hash 计算以避免冲突,实现与 scoped CSS一样作用域的效果
const $vRootStyle = useCssModule('root-moudle')
console.log('$vRootStyle.title =>', $vRootStyle.title)

// 通过 provide 传给某个遥远的子孙后代一个对象信息
provide('uniqueKey', {
   
    author: '帅龍之龍', date: '2023-02-06'})
</script>

<style lang="less" scoped>
  .v-root {
   
   
    padding: 50px 100px;

    .v-root-main {
   
   
      border: 1px solid #eee;

      h1 {
   
   
        background-color: #f8f8f8;
        border-bottom: 1px solid #eee;
        text-align: center;
        font-weight: lighter;
      }

      .v-child {
   
   
        width: auto;
        margin: 50px 100px;
        border: 1px solid #eee;
        border-radius: 4px;
      }

      .operation {
   
   
        padding: 10px;
        border-top: 1px solid #eee;
        text-align: center;
      }
    }
  }
</style>

<style module="root-moudle" lang="less">
  .title {
   
   
    color: rgb(0, 167, 97);
  }
</style>

(2)/src/views/Example/ScriptSetup/vChild.vue

<template>
  <div class="v-child">
    <h3 :class="$vChildStyle.title">vChild子组件</h3>

    <div class="infomation">
      <p>用户:{
   
   {
   
    username }}</p>
      <p>技能:{
   
   {
   
    newSkills }}</p>
      <p>码龄:{
   
   {
   
    age }}</p>
    </div>

    <div class="operation">
      <el-button size="small" type="primary" @click="handleClick($event)">
        <el-icon :size="18"><Check /></el-icon>
        <span>点击传递 emits 参数给父组件</span>
      </el-button>

      <br /><br />

      <el-button size="small" type="warning" @click="handleHttpRequestEvent($event)">
        <el-icon :size="18"><Check /></el-icon>
        <span>点击发起一个HTTP的GET请求</span>
      </el-button>

      <br /><br />

      <el-button size="small" type="danger" @click="handleAddAISkillClick($event)">
        <el-icon :size="18"><Check /></el-icon>
        <span>学习AI技能</span>
      </el-button>
    </div>

    <!-- 匿名插槽 -->
    <slot></slot>

    <!-- 具名插槽 -->
    <slot name="sign"></slot>
  </div>
</template>

<script setup>
import {
   
    defineProps, defineEmits, ref, getCurrentInstance, reactive, useAttrs, useSlots, useCssModule, inject, computed, watch, nextTick } from 'vue'

const {
   
    proxy } = getCurrentInstance()

const background = '#f8f8f8' // 常量声明,设置子组件标题的CSS背景颜色

// 子组件通过 defineProps 接收父组件的 props 参数
defineProps({
   
   
  username: {
   
   
    type: String,
    default: ''
  }
})

// 子组件通过 defineEmits 传递 emits 参数给父组件
const emit = defineEmits(['handleFromVChildClick'])
const handleClick = () => {
   
   
  const json = {
   
    msg: '这是一条来自子组件的消息 ~' }
  emit('handleFromVChildClick', json)
}

/**
 * 点击发起一个HTTP请求
 */
async function handleHttpRequestClick() {
   
   
  const res = await proxy.$http.getXXX()
  console.log('handleHttpRequestClick =>', res)
}

/**
 * 发起一个HTTP请求事件
 */
const handleHttpRequestEvent = () => {
   
   
  (async () => {
   
   
    const res = await proxy.$http.getXXX()
    console.log('匿名请求 =>', res)
  })()
}

/**
 * 学习AI技能点击事件
 */
const handleAddAISkillClick = () => {
   
   
  const skill = 'AI'
  if (!skills.includes(skill)) {
   
   
    skills.push(skill)
    skills.sort()
    proxy.$message({
   
   
      message: 'AI技能学习成功!',
      type: 'success',
      duration: 1000
    })

    // nextTick 是在下次 DOM 更新循环结束之后执行延迟回调,在修改数据之后使用$nextTick(),则可以在回调中获取更新后的 DOM
    nextTick(() => {
   
   
      age.value = age.value + 2
    })
  } else {
   
   
    proxy.$message({
   
   
      message: 'AI技能已拥有啦!',
      type: 'warning',
      duration: 1000
    })
  }
}

let age = ref(25) // 响应式数据声明,建议基本数据类型
const skills = reactive([ // 响应式数据声明,建议复杂数据类型,若使用 reactive 定义响应式数据,其必须为对象或数组,不能是基本类型,如数字、字符串、布尔值等
  'Java',
  'SpringBoot',
  'SpringCloud',
  'Vue',
  'React',
  'Html5+Css3+Js+Jquery',
  'MySQL'
])
// 二者区别:ref 需要通过.value获取值

const fn = (e) => {
   
    // 定义一个方法名为 fn 的箭头函数
  console.info('Hello,World!', e)
}

// 当动态修改被computed的原数据时,computed的新数据也会动态改变,其使用场景如后端只返回一个数组,由前端完成静态分页
const newSkills = computed(() => {
   
   
  const str = skills.join(' | ')
  return str
})

// watch监听,watch(WatcherSource, Callback, [WatchOptions]),当监听值引用数据(基本数据类型)时,第一个参数为变量,当监听地址引用数据(对象、数组等)时,第一个参数为对象方法
watch(
  () => {
   
   
    return {
   
    ...skills };
  },
  (newValue, oldValue) => {
   
   
    console.log('watch =>', newValue, oldValue);
  },
  {
   
    deep: true }
)

// 子组件通过 defineExpose 暴露指定的属性给父组件
defineExpose({
   
   
  age,
  skills,
  fn
})

// 通过 useAttrs 获取该实例组件的所有属性信息
const attrs = useAttrs()
console.log('attrs =>', attrs)

// 通过 useSlots 获取该实例组件的所有插槽信息
const slots = useSlots()
console.log('所有插槽 =>', slots)
console.log('匿名插槽 =>', slots.default())
console.log('具名插槽(sign) =>', slots.sign())

// 通过 useCssModule 和 <style moudle> 标签对生成的CSS类名做 hash 计算以避免冲突,实现与 scoped CSS一样作用域的效果
const $vChildStyle = useCssModule()
console.log('$vChildStyle.title =>', $vChildStyle.title)

// 通过 inject 接收来自某个遥远的祖先一个对象信息
const uniqueKey = inject("uniqueKey")
console.info('uniqueKey =>', uniqueKey)
</script>


<style lang="less" scoped>
  .v-child {
   
   

    h3 {
   
   
      background-color: v-bind(background);
      border-bottom: 1px solid #eee;
      text-align: center;
      font-weight: lighter;
    }

    .infomation {
   
   
      padding: 10px;
      font-size: 14px;
    }

    .operation {
   
   
      padding: 10px;
      border-top: 1px solid #eee;
      border-bottom: 1px solid #eee;
      text-align: center;
    }
  }
</style>

<style module lang="less">
  .title {
   
   
    color: rgb(255, 65, 97);
  }
</style>

二、运行效果

目录
相关文章
|
7天前
|
JavaScript
Vue3中路由跳转的语法
Vue3中路由跳转的语法
111 58
|
5天前
|
JavaScript 索引
Vue 2和Vue 3的区别以及实现原理
Vue 2 的响应式系统通过Object.defineProperty来实现,它为对象的每个属性添加 getter 和 setter,以便追踪依赖并响应数据变化。
20 9
|
7天前
|
JavaScript 开发工具
vite如何打包vue3插件为JSSDK
【9月更文挑战第10天】以下是使用 Vite 打包 Vue 3 插件为 JS SDK 的步骤:首先通过 `npm init vite-plugin-sdk --template vue` 创建 Vue 3 项目并进入项目目录 `cd vite-plugin-sdk`。接着,在 `src` 目录下创建插件文件(如 `myPlugin.js`),并在 `main.js` 中引入和使用该插件。然后,修改 `vite.config.js` 文件以配置打包选项。最后,运行 `npm run build` 进行打包,生成的 `my-plugin-sdk.js` 即为 JS SDK,可在其他项目中引入使用。
|
7天前
|
JavaScript 开发者
彻底搞懂 Vue3 中 watch 和 watchEffect是用法
彻底搞懂 Vue3 中 watch 和 watchEffect是用法
|
5天前
|
JavaScript 调度
Vue3 使用 Event Bus
Vue3 使用 Event Bus
10 1
|
5天前
|
JavaScript
Vue3 : ref 与 reactive
Vue3 : ref 与 reactive
9 1
vue3 reactive数据更新,视图不更新问题
vue3 reactive数据更新,视图不更新问题
|
6天前
|
JavaScript
|
6天前
vue3定义暴露一些常量
vue3定义暴露一些常量
|
5天前
Vue3 使用mapState
Vue3 使用mapState
9 0