百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术分类 > 正文

vue3 script setup 语法糖

ztj100 2024-11-26 11:15 16 浏览 0 评论

Loong Panda


<script setup> 是在单文件组件 (SFC) 中使用 组合式 API 的编译时语法糖。相比于普通的 <script> 语法,它有更简洁的代码,由于处于同一作用域,因此的运行时性能会更好。


响应式变量

<script setup>
	// vue3和vue2最大的区别就是响应式变量
  import { ref, toRef, toRefs, reactive, onMounted } from 'vue';
  const val1 = ref(0); // 创建任意数据类型的响应式变量
  const val2 = reactive({ num: 1 }); // 创建引用类型的响应式对象
  const { newVal } = toRefs(val2); // 将响应式对象转换为普通对象
  const val3 = toRef(val2, 'num'); // 将响应式对象num2中num字段创建为一个新的响应式变量
  onMounted(() => {
    val1.value = Date.now(); // 修改ref创建的变量
    val2.num = Date.now() // 修改reactive创建的变量
  });
</script>

函数

<template>
	<el-button size="small" @click="onClick">点击</el-button>
</template>
<script setup>
  
  function onClick() {
    // ....
  };
</script>

计算属性(computed)

<script setup>
  import { computed, ref } from 'vue'
  const num = ref(1)
  const calc = computed(() => {
  	return num.value * 2
  })
</script>

观察属性(watch)

<script setup>
  import { watch, reactive } from 'vue'
  const obj = reactive({
  	count: 1
  })
  // 监听count
  watch(
  	() => obj.count,
  	(newVal, oldVal) => {
      
    },
    {
      immediate: true, // 立即执行
      deep: true // 深度监听
    }
  )
</script>

父子组件传值 props 和 emit


子组件
  
<template>
  <span>{{ dataId }}</span> // 展示父级传递过来的参数
  <el-button size="small" @click="onUpdate">更新</el-button>
</template>
<script setup>

  // 声明 props
  const props = defineProps({
    dataId: {
      type: String,
      default: ''
    }
  })
  // 声明 emit 事件,事先需要声明好事件名,如on-update
  const emit = defineEmits(['on-update'])

  const onUpdate = () => {
    // 执行 on-update 事件
    emit('on-update', Date.now())
  }
</script>

父组件

<template>
	<child :data-id="chidDataId" @on-update="onUp"></child>
</template>
<script setup>
  import child from './child.vue';
  import { ref } from 'vue';
  const chidDataId = ref(100)

  // 接收子组件触发的方法
  function onUp(name) {
  	//
  }
</script>

七、双向绑定 v-model

子组件

<template>

<span @click="changeInfo">我叫{{ modelValue }},今年{{ age }}岁</span>

</template>

<script setup>

// import { defineEmits, defineProps } from 'vue'

// defineEmits和defineProps在<script setup>中自动可用,无需导入

// 需在.eslintrc.js文件中【globals】下配置【defineEmits: true】、【defineProps: true】

defineProps({

modelValue: String,

age: Number

})

const emit = defineEmits(['update:modelValue', 'update:age'])

const changeInfo = () => {

// 触发父组件值更新

emit('update:modelValue', 'Tom')

emit('update:age', 30)

}

</script>

父组件

<template>

// v-model:modelValue简写为v-model

// 可绑定多个v-model

<child v-model="state.name" v-model:age="state.age"></child>

</template>

<script setup>

import child from './child.vue'

import { reactive } from 'vue'

const state = reactive({

name: 'Jerry',

age: 20

})

</script>


路由

<script setup>
  import { useRoute, useRouter } from 'vue-router'

  const route = useRoute();
  const router = useRouter();

	// 路由跳转
  router.push('/home')
  
	// 获取路由实例,及路由信息
  console.log(route.query)
  
</script>


路由守卫

<script setup>
  import { onBeforeRouteLeave, onBeforeRouteEnter } from 'vue-router'

  onBeforeRouteLeave((to, from, next) => {
    next()
  })
  onBeforeRouteEnter((to, from, next) => {
  	next()
  })
</script>


全局状态管理器

<script setup>
  import { useStore } from 'vuex'
  const store = useStore()

  // 获取state
  store.state.xxx
  // 触发mutations的方法
  store.commit('fnName')
  // 触发actions的方法
  store.dispatch('fnName')
  // 获取Getters
  store.getters.xxx
</script>

原型挂载/绑定与使用

----绑定--------------------------------------------------------------------
// main.js
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
// 获取原型
const prototype = app.config.globalProperties
// 绑定参数
prototype.$ajax = ajax

----使用--------------------------------------------------------------------

<script setup>
  import { getCurrentInstance } from 'vue'
  const { proxy } = getCurrentInstance()

  proxy.$ajax(url, {})
    .then(res => {
  		// .....
  	})
</script>

生命周期

vue3和vu2周期最大的区别是vue3用setup替代了beforeCreate 和 created,通俗的说fa就是说原来在beforeCreate 和 created写的代放在码在setup里就行了。其他的周期使用前缀“on”,

比如: onMounted(() => {})


选项式 API

Hook inside setup

beforeCreate

Not needed*

created

Not needed*

beforeMount

onBeforeMount

mounted

onMounted

beforeUpdate

onBeforeUpdate

updated

onUpdated

beforeUnmount

onBeforeUnmount

unmounted

onUnmounted

errorCaptured

onErrorCaptured

renderTracked

onRenderTracked

renderTriggered

onRenderTriggered

activated

onActivated

deactivated

onDeactivated

相关推荐

如何将数据仓库迁移到阿里云 AnalyticDB for PostgreSQL

阿里云AnalyticDBforPostgreSQL(以下简称ADBPG,即原HybridDBforPostgreSQL)为基于PostgreSQL内核的MPP架构的实时数据仓库服务,可以...

Python数据分析:探索性分析

写在前面如果你忘记了前面的文章,可以看看加深印象:Python数据处理...

CSP-J/S冲奖第21天:插入排序

...

C++基础语法梳理:算法丨十大排序算法(二)

本期是C++基础语法分享的第十六节,今天给大家来梳理一下十大排序算法后五个!归并排序...

C 语言的标准库有哪些

C语言的标准库并不是一个单一的实体,而是由一系列头文件(headerfiles)组成的集合。每个头文件声明了一组相关的函数、宏、类型和常量。程序员通过在代码中使用#include<...

[深度学习] ncnn安装和调用基础教程

1介绍ncnn是腾讯开发的一个为手机端极致优化的高性能神经网络前向计算框架,无第三方依赖,跨平台,但是通常都需要protobuf和opencv。ncnn目前已在腾讯多款应用中使用,如QQ,Qzon...

用rust实现经典的冒泡排序和快速排序

1.假设待排序数组如下letmutarr=[5,3,8,4,2,7,1];...

ncnn+PPYOLOv2首次结合!全网最详细代码解读来了

编辑:好困LRS【新智元导读】今天给大家安利一个宝藏仓库miemiedetection,该仓库集合了PPYOLO、PPYOLOv2、PPYOLOE三个算法pytorch实现三合一,其中的PPYOL...

C++特性使用建议

1.引用参数使用引用替代指针且所有不变的引用参数必须加上const。在C语言中,如果函数需要修改变量的值,参数必须为指针,如...

Qt4/5升级到Qt6吐血经验总结V202308

00:直观总结增加了很多轮子,同时原有模块拆分的也更细致,估计为了方便拓展个管理。把一些过度封装的东西移除了(比如同样的功能有多个函数),保证了只有一个函数执行该功能。把一些Qt5中兼容Qt4的方法废...

到底什么是C++11新特性,请看下文

C++11是一个比较大的更新,引入了很多新特性,以下是对这些特性的详细解释,帮助您快速理解C++11的内容1.自动类型推导(auto和decltype)...

掌握C++11这些特性,代码简洁性、安全性和性能轻松跃升!

C++11(又称C++0x)是C++编程语言的一次重大更新,引入了许多新特性,显著提升了代码简洁性、安全性和性能。以下是主要特性的分类介绍及示例:一、核心语言特性1.自动类型推导(auto)编译器自...

经典算法——凸包算法

凸包算法(ConvexHull)一、概念与问题描述凸包是指在平面上给定一组点,找到包含这些点的最小面积或最小周长的凸多边形。这个多边形没有任何内凹部分,即从一个多边形内的任意一点画一条线到多边形边界...

一起学习c++11——c++11中的新增的容器

c++11新增的容器1:array当时的初衷是希望提供一个在栈上分配的,定长数组,而且可以使用stl中的模板算法。array的用法如下:#include<string>#includ...

C++ 编程中的一些最佳实践

1.遵循代码简洁原则尽量避免冗余代码,通过模块化设计、清晰的命名和良好的结构,让代码更易于阅读和维护...

取消回复欢迎 发表评论: