Vue3 Composition Api 体验心得(或持续更新?)

431 阅读2分钟

内容简介

自从Vue3公布RFC阶段后,摸鱼有段时间决定做个Vue3体验产出,不足之处还望指点。

1. 适用于Composition Api场景

  • 描述:

Vue2旧写法中,当业务代码量达到一定程度时候,datamethods割裂感十分明显,时常消耗多余的精力在代码的上下关系。

Vue3 Composition Api的出现让业务代码更加有效地分明。

  • 解决:

  • 使用:

Vue Options

export default {
  data() {
    return {
      a: {
        version: 2,
        state: []
      },
      b: 'string',
      c: 114514
      // ...
    }
  },
  computed: {
    c2() {
      return this.$store.state.count * 2
    }
    // ...
  },
  methods: {
    handleRouter(pathName) {
      if (this.$route.name === pathName) {
        // do something
      }
    },
    handleVuex(someData) {
      this.$store.commit('something', someData)
      // do something
    }
    // ...
  }
}

Vue Composition

import { computed, ref, reactive } from 'vue';
import { useStore } from 'vuex';
import { useRoute } from 'vue-router';
export default {
  setup() {
    // vuex do something
    const store = useStore();
    
    const c2 = computed(() => store.state.count * 2);
    
    const handleVuex = (someData) => {
      this.$store.commit('something', someData)
      // do something
    };
    
    // some data
    const a = reactive({
      version: 2,
      state: []
    });
    const b = ref('string');
    const c = ref(114514);
    
    const route = useRoute();
    
    // some method 
    const handleRouter = (pathName) => {
      if (route.name === pathName) {
        // do something
      }
    };
    
    // 暴露到template并进行使用
    return {
      a,
      b,
      c,
      c2,
      handleVuex,
      handleRouter
    };
    
  }
}

Vue Composition更应该是业务代码清晰,是可以让业务代码更加分离,所以试着单独写成一个或多个js文件进行导入。

// myFunction.js
import { reactive, ref, computed, toRefs } from "vue";
import { useStore } from 'vuex';
import { useRoute } from 'vue-router';
// 一个组合逻辑函数
export const useFunction() {
  const store = useStore();
    
  const a = reactive({
    version: 2,
    state: []
  });
  const c2 = computed(() => store.state.count * 2);
    
  const handleVuex = (someData) => {
    this.$store.commit('something', someData)
    // do something
  };
  
  return {
    a: toRefs(a), // 值得一提的是建议此处 toRefs 否则外部解构会断开响应式
    c2,  // computed 可直接导出
    handleVuex
  }
}
// 另一个组合逻辑函数
export const useAnotherFunction() {
  const b = ref('string');
  const c = ref(114514);
    
  const route = useRoute();
   
  // some method 
  const handleRouter = (pathName) => {
    if (route.name === pathName) {
      // do something
    }
  };
  
  return {
    b,
    c,
    hanldeRouter
  }
}


// myComponents.vue
import { useFunction, useAnotherFunction } from './myFunction.js'
export default {
  setup() {
    const { a, c2, handleVuex } = useFunction();
    const { b, c, handleRouter } = useAnotherFunction();
    
    // = w = 突然心情极度舒畅
    
    // 暴露到template并进行使用
    return {
      a,
      b,
      c,
      c2,
      handleVuex,
      handleRouter
    };
    
  }
}

后续

目的还是尝试写文,目前在利用Vue3做一个个人爱好项目,后续如果有复杂功能值得产出的将会更新文章,大佬轻喷 Orz