vue3中script setup

1.属性和方法

属性和方法无需返回,直接使用

<template>
  <div>
    <Foo />
    <h2 @click="increment">{{ count }}</h2>
  </div>
</template>

<script setup>
  import { ref } from 'vue'
  import Foo from './components/Foo.vue'

  const count = ref(0)
  const increment = () => count.value++
</script>

会被编译为

// 导入的模块会被抽离到模块级别
import { ref } from 'vue'
import Foo from './components/Foo.vue'

export default {
  setup() {
    const count = ref(0)
    const increment = () => count.value++
    	
    // 这是一个返回h函数的render函数
    // 因为被编译到了setup函数中,所以可以直接访问顶层定义的属性和方法
    return () => ([
      h(Foo, null, ''),
      h('h2', {
        count,
        onClick: increment
      }, count)
    ])
  }
}

2.组件自动注册

<template>
  <div>
    <Foo />
  </div>
</template>

<!-- 在script标签上添加setup属性,以使用 script setup 语法 -->
<script setup>
  import Foo from './components/Foo.vue'
</script>

3.props和emits

子组件

<template>
  <div>
    <h2>{{ count }}</h2>
    <button @click="$emit('increment')">+1</button>
    <button @click="decrement">-1</button>
  </div>
</template>

<script setup>
  // 接收props,并返回一个对象,可以在js中使用props来获取传入的数据
  const props = defineProps({
    count: {
      type: Number,
      default: 0
    }
  })

  // 声明需要触发的事件,返回一个emit函数,作用和this.$emit函数的作用是一致的
  const emit = defineEmits(['increment', 'decrement'])

  const decrement = () => emit('decrement')
</script>

父组件

<template>
  <div>
    <Foo :count="count" @increment="increment" @decrement="decrement" />
  </div>
</template>

<script setup>
  import { ref } from 'vue'
  import Foo from './components/Foo.vue'

  const count = ref(0)
  const increment = () => count.value++
  const decrement = () => count.value--
</script>
  • defineProps 和 defineEmits 是编译器宏(compiler macros )

    只能在 <script setup> 中使用。它们不需要被导入,并且在处理 <script setup> 时被编译掉。

  • 传递给 defineProps 和 defineEmits 的选项将被从 setup 中提升到模块范围。

    因此,这些选项不能引用在 setup 作用域内声明的局部变量。这样做会导致一个编译错误。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值