首先说一下组合api的特点
1.更加直观,接近原生js
2.按需加载
3.没有this,降低了耦合性
steup()相当于created生命周期需要return返回才可以在模板中使用
setup(){
// 执行时机:created
}
ref 值类型响应对象
在setup访问count值要通过count.value引用
const count = ref(0)
console.log(count.value) // 0
可以作为dom引用
const inp = ref(null)
inp.value.innerText
<p ref="inp">你好</p>
reactive引用类型响应式
list.push(xxx)
watch监听
watch("count",(navl,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 在原有生命周期添加on
onBeforeMount 挂载前
onMoutend 挂载完毕
onBeforeUpdate 更新前
onUpdated 更新完毕
onUnMount 卸载前
onUnMounted 卸载完毕
全局配置
app.config.globalProperties.xxx=yyy
getCurrentlnstance 获取当前实例
不推荐使用(this)
const app = getCurrentInstance{},appCountext
const xxx = app.config.glovalPropertites.xxx 获取全局的方法
set使用vuex
import {useStore} from "vuex" const store = useStore{}
store.commit("user/addScore",v)
setup 使用路由
import {useRouter,useRoute} from "vue-router"
const router = useRouter(); const route = userRoute() 等同于this.$router 和 this.$route
setup(props,context) 参数
props 传入参数(响应式)
context
attrs 属性
emit 事件发送器(同$enit)
slots插槽 同$slots
expose 暴露数据