setup组合式Api

169 阅读1分钟

区别

vue2中的使用方式被叫做options api,配置式的使用

<script >
export default{
    data(){},
    //方法
    methods:{},
    watch:{},
    computed:{}
}
</script>

vue3中新增了setup被叫做composition api,数据定义、数据监听、函数集中在一起。个人理解更方便组件封装,hook功能封装。简单的业务逻辑放在一起也更简洁。复杂点的功能就不适合放在一起了,反而降低了代码的可读性

<script setup >
import { ref, reactive, } from "vue";
const text = ref('');
const obj = reactive({})
const changeDis = () => {
    text.value = '修改文本'
    obj.name = '小刘同学'
}
</script>

用法

两种方式

1、一种类似options api的写法。需要在setup种返回响应式变量和函数,这种支持下面继续添加一些vue2写法

注:如果使用ts的话,导出的对象需要包一层defineComponent 使用了解,用于类型推导

<script>
import { ref, defineComponent, reactive } from "vue";
export default {
  setup() {
    const text = ref('');
    return {text}
  },
  data () {
      return {t3: '关羽'}
  },
  methods: {
      cT3() {
          this.t3 = '张飞'
      }
  }
}
</script>

2、setup 语法糖,在script标签中传setup, 不用再return定义的响应式变量和函数,而且引入的组件不用在conponents里面声明可以直接在模板中使用。扩展使用的话就在加一个script 标签

<template>
    <button @click="changeDis">changeDis</button>
    <CusComp />
</template>
<script setup >
import { ref, reactive, } from "vue";
import CusComp from './cusComp.vue'

const text = ref('');

const changeDis = () => {
    text.value = '修改文本'
}
</script>
<script >
    export default 
        data () {
            return {
                text2: 3333
            }
        }
    }
</script>

参数

setup(props, context) {}
  • props 父级传参
  • context 包括attrs,slots, emit, expose

具体使用会在组件通讯详说

关于this

不要使用this获取组件的实例。官方解释:在 setup() 内部,this 不是该活跃实例的引用,因为 setup() 是在解析其它组件选项之前被调用的,所以 setup() 内部的 this 的行为与其它选项中的 this 完全不同。