1、组合api特点
- 更加直观,接近原生js
- 按需加载
- 没有this,降低了耦合性,提高了复用性
2、setup()
- 相当于created生命周期
- 需要return返回,在模板中使用
3、ref(值类型 响应对象)
- const count = re(5)
- 在setup 访问count值,const.value来访问
- 可以作为dom引用
const inp = ref(null)
<p ref="inp">
inp.value.innterText
4、reactive(引用类型 响应式)
const list = reactive(默认值)
错误: list = xxx 直接赋值破坏了引用
正确用法: list.push(xxx)
5、watch (监听)
-
watch("count",(nval,oval)=>{ //执行回调函数})
6、watchEffect(监听效果)
- 只有引用的数据变化都会执行回调函数
- const stop = watchEffect(()=>{localStorage.setItem("count",count.value)})
- stop 用来停止监听 stop()
7、computed(计算)
- computed (()=>count.value*2 )
- computed ("age",{get(){return count.value},set(v){count.value = v}})
8、生命周期
- 没有 created,在原有的生命周期添加 on
- onBeforeMount,挂载前
- onMounted,挂载完毕
- onBeforeUpdate,更新前
- onUpdated,更新完毕
- onUnMount,卸载前
- onUnMounted,卸载完毕
9、全局配置
- app.config.globalProperties.xxx = yyy
10、getCurrentInstance(获取当前实例)
- 不推荐使用(this)
- const app =getCurrentlnstace().appContext
- const xxx = app.config.globalPropertites.xxx获取到全局的而方法
11、setup 使用vuex
- import {useStore} from 'vuex'
- const store = useStore()
- store.commit("user/addScore" ,v)
12、setup 使用路由
- import {useRouter,useRoute} from 'vue-router'
- const router = useRouter();
- const route = useRoute()
- 等同于this.$router和this.$route
13、setup(props,context)(参数)
- props传入参数(响应式)
- context:
attrs属性
emit事件发送器(同$emit>)
slots插槽 同$slots
expose暴露数据