vue3 setup函数语法糖

Vue3引入的<scriptsetup>语法简化了组件的编写,无需exportdefault和setup函数。它可以用于直接声明模板中的变量和方法,如直接定义constmsg和函数log。此外,它支持响应式数据(ref)和组件导入,无需显式注册。defineProps和defineEmits帮助处理props和事件,同时允许注入CSS变量以实现动态样式。
摘要由CSDN通过智能技术生成

1. 优点

  • 省去export default 导出
  • 省去setup函数及返回
<template>
  <button @click="log">{{ msg }}</button>
</template>

<script setup>
// 变量
const msg = 'Hello!'

// 函数
function log() {
  console.log(msg)
}
</script>

2. 其他用法

  • 响应式数据

<template>
  <button @click="count++">{{ count }}</button>
</template>

<script setup>
import { ref } from 'vue'

const count = ref(0)
</script>


  • 使用组件  省去组件注册
<template>
  <MyComponent />
</template>

<script setup>
import MyComponent from './MyComponent.vue'
</script>

  • `defineProps`、`defineEmits`和`useContext`  代替setup函数中的 props与context

<template>
  <span>{{ props.msg }}</span>
</template>
​
<script setup>
import { useContext, defineProps, defineEmits } from 'vue'。

const emit = defineEmits(['change', 'delete'])
const ctx = useContext()
const props = defineProps({  
  msg: String,
})
  • css 变量注入
<template>
  <span>123</span>  
</template>
 
<script setup>
  import { reactive } from 'vue'
 
  const state = reactive({
    color: 'green'
  })
</script>
  
<style scoped>
  span {
    color: v-bind('state.color');
  }  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值