getCurrentInstance 获取当前组件实例

<template>
</template>
<script>
import { getCurrentInstance } from 'vue';
export default {
  name: 'App',
  setup() {
    const instance = getCurrentInstance();
    console.log(instance);
  }
}
</script>

Untitled

setup 读取值

import { getCurrentInstance, ComponentInternalInstance } from 'vue';
 
const { appContext } = <ComponentInternalInstance>getCurrentInstance()
 
console.log(appContext.config.globalProperties.$env);
 
// 推荐第二种方式
 
import {ref,reactive,getCurrentInstance} from 'vue'
const app = getCurrentInstance()
console.log(app?.proxy?.$filters.format('js'))

options api 和 composition api 区别

import { onMounted } from 'vue';
export default {
  mounted() {}, // options api
  setup() {
    onMounted(() => {}); // composition api
  }
}

beforeCreate 和 created 由 setup 代替

onBeforeMount、onMounted 和 onBeforeUpdate、onUpdated

<template>
  <div>{{ count }}</div>
</template>
<script>
import {
  getCurrentInstance,
  ref,
  onBeforeMount,
  onMounted,
  onBeforeUpdate,
  onUpdated,
  watchEffect
  } from 'vue';
export default {
  name: 'App',
  setup() {
    const count = ref(0);
    setTimeout(() => {
      count.value = 1;
    }, 1000);
    watchEffect(() => {
      console.log('watchEffect count value:', count.value);
    });
    onBeforeMount(() => console.log('onBeforeMount'));
    onMounted(() => console.log('onMounted'));
    onBeforeUpdate(() => console.log('onBeforeUpdate'));
    onUpdated(() => console.log('onUpdated'));
    return {
      count
    }
  }
}
</script>

Untitled

把 watchEffect 中的 flush 设置为 post 时,watch在 beforeUpdate 之后执行

watchEffect(() => {
  console.log('watchEffect count value:', count.value);
}, {
  flush: 'post'
});

Untitled