替代 Options API的写法

ue3转变

    从 vue3 开始,由 setup 替代 vue2 data、methods、watch等 ,这样可以避免一个功能的代码逻辑拆分到各个属性中而变得难以阅读
    vue3 setup 的这种写法可以更好的使用 TypeScript

注意事项:

    setup 函数里面不可以使用 this, 因为setup里面没有绑定 this
    setup(){console.log(this)}; // undefined
    setup 里面定义的数据默认不是响应式的,即数据发生改变,但是页面数据不刷新。需要使用 ref reactive 等响应式API

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

<script>
import {
  ref,
  reactive,
  computed,
  watchEffect,
  watch,
  onBeforeMount,
  onMounted,
  onBeforeUpdate,
  onUpdated,
  onBeforeUnmount,
  onUnmounted,
} from "vue";

export default {
  // 传统的Options API
  /*
  data() {
    return {};
  },
  computed: {},
  watch: {},
  methods: {},
  created() {},
  mounted() {},
  */

  // Composition API
  setup() {
    // 定义数据
    const obj = {};
    const data = [];

    // 定义响应式数据
    let refCounter = ref(0);
    let reactiveObj = reactive({ name: "hello", age: 20 });
    let reactiveInfo = reactive({ firstName: "Foo", lastName: "Bar" });

    // 定义计算属性 getter 写法
    // const fullName = computed(
    //   () => reactiveInfo.firstName + " " + reactiveInfo.lastName
    // );

    // 计算属性getter setter 写法
    const fullName = computed({
      get: () => reactiveInfo.firstName + " " + reactiveInfo.lastName,
      set: (newVal) => {
        let name = newVal.split(" ");
        reactiveInfo.firstName = name[0];
        reactiveInfo.lastName = name[1];
      },
    });

    // 定义侦听器
    watchEffect(() => {
      console.log("watchEffect自动侦听器");
    });
    watch(
      () => {
        console.log("watch手动侦听器");
      },
      { deep: true, immediate: true } // 开启深度侦听和立即执行侦听器
    );

    // 定义方法
    const increment = () => {
      refCounter.value++; // ref 包裹的数据是 ref对象,取数据时需要使用 ref对象.value
      reactiveObj.age++;
    };

    // 定义生命周期函数 移除了 beforeCreate、created 这两个生命周期的内容可以直接在 setup函数中定义
    onBeforeMount(() => {
      console.log("onBeforeMount");
    });
    onMounted(() => {
      console.log("onMounted");
    });
    onBeforeUpdate(() => {
      console.log("onBeforeUpdate");
    });
    onUpdated(() => {
      console.log("onUpdated");
    });
    onBeforeUnmount(() => {
      console.log("onBeforeUnmount");
    });
    onUnmounted(() => {
      console.log("onUnmounted");
    });

    // 返回数据方法等让 template 模板使用
    return {
      refCounter,
      reactiveObj,
      reactiveInfo,
      fullName,
      increment,
    };
  },
};
</script>

<style scoped></style>

 

posted @ 2021-09-30 15:47  熊大大001(前端开发)  阅读(222)  评论(0)    收藏  举报