setup/组合api 最新知识点总结

 组合api的特点

 setup()

ref值类型 响应对象

reactive引用类型 响应式

watch监听

watchEffect监听效果

computed计算

生命周期

全局配置

getCurrentInstance获取当前实例

setup使用vuex

setup使用路由

setup(props,context)参数

setup语法糖


 组合api的特点

    1.更加直观,接近原生js
    2.按需加载
    3.没有this,降低耦合性,提高复用性

 setup()

    相当于created生命周期
    需要return返回,在模板中使用

ref值类型 响应对象

 在setup访问count值 需要用count.value 来访问

const count=ref(5)
//可以作为dom引用
const inp = ref(null)
<p ref="inp" ></p>
inp.value.innerText

reactive引用类型 响应式

const list = reactive(默认值)

reactive类型的赋值方式:
wrong: list=xxx; 直接赋值,破环引用
right: list.push(xxx)

watch监听

watch("count",(nval,oval)=>{
  //执行回调函数
})

watchEffect监听效果

只要引用的数据变化都会执行回调函数

const stop=watchEffect(()=>{
    localStorage.setItem("count",count.value)
})

stop 可以用来停止监听

stop();

computed计算

 computed("count2",()=>{count.value*2})
    computed("age",{
    get(){return count.value},
    set(v){count.value=v}
})

生命周期

没有created,因为setup相当于created生命周期
在原有生命周期前添加on

全局配置

app.config.globalProperties.xxx=yyy

getCurrentInstance获取当前实例

不推荐使用(this)
获取到全局的方法:   

const app = getCurrentInstace().appContext
const xxx = app.config.globalProperties.xxx

setup使用vuex

import {useStore} from 'vuex'
const store = useStore()
store.commit("use/addScore",v)

setup使用路由

import {useRouter,useRoute} from 'vue-router'
const route = useRoute();
const router = useRouter();

等同于this.$router和this.$route

setup(props,context)参数


    props 传入参数(响应式)
   context
        attrs 属性
        emit 事件发送器 (同$emit)
        slots 插槽 同$slots
        expose 暴露数据

setup语法糖

<script setup></script>

 1.不需要导出

 2.组件不需要注册

<template>
    <div>
        <steper></steper>
    </div>
</template>

//引入后不需要在注册
<script  setup>
     import steper  "../components/steper.vue"
</script>

猜你喜欢

转载自blog.csdn.net/TeAmo__/article/details/123533368
今日推荐