vue3 setup的用法

单文件组件 <script setup>

基本用法:

<template>
  <button @click="log">{
   
   { msg }}</button>
</template>
<script setup>
const msg = 'Hello!'
function log() {
  console.log(msg)
}
</script>

接受props值和emit事件:

<script setup>
const props = defineProps({
  foo: String
})

// 接口设置,给props定义类型
export interface Props {
  msg?: string
  labels?: string[]
}

// props 设置默认值
withDefaults(defineProps<Props>(), { 
  msg: 'hello',
  labels: () => ['one', 'two']
})

// 触发事件
const emit = defineEmits(['change', 'delete'])
emit('change')
</script>

组合式 API:setup()

基本用法:

<template>
  <button @click="count++">{
   
   { count }}</button>
</template>
<script>
import { ref } from 'vue'

export default {
  setup() {
    const count = ref(0)

    // 返回值会暴露给模板和其他的选项式 API 钩子
    return {
      count
    }
  },

  mounted() {
    console.log(this.count) // 0
  }
}
</script>

接受props值和emit事件: 

<template>
  <button @click="count++">{
   
   { count }}</button>
</template>
<script>
import { ref } from 'vue'

export default {
  props: {
    title: String,
    default: ''
  },
  setup(props, context) {
    const count = ref(0)
    // 使用props中的值
    console.log(props.title)
    // emit 事件
    ontext.emit('事件命')

    // 返回值会暴露给模板和其他的选项式 API 钩子
    return {
      count
    }
  },

  mounted() {
    console.log(this.count) // 0
  }
}
</script>

猜你喜欢

转载自blog.csdn.net/qq_44694453/article/details/127057234