Vue开发过程中的一次使用mixin优化代码

引入原因: 需求更改导致需要在跳转入口出进行大量的api调用和判断路由跳转. 修改的地方涉及到6个地方。最初是无脑进行代码copy+paste,后来考虑到维护的成本和容易遗漏,使用mixin抽取共同方法达到理想目的,见代码:

1: 定义mixin文件,methods里有一个handleToLink方法

/**
 * this mixin file will be used in below places:
 * 1: src\views\home\aaa.vue
 * 2: src\views\home\bbb.vue
 * 3: src\views\portal\ccc.vue
 * 4: src\views\portal\ddd.vue
 */
export default {
  methods: {
    // params include 2 fields
    handleToLink(params) {
      console.info('mixin link method')
      this.$store.dispatch('xxxx/xxxxxx').then(() => {
        let user = this.$store.getters.user
        if (user.status == 1) {
          this.$message.warning('xxxxxxxxxx')
          this.$router.push('/logicPage_A')
        } else if (user.status == 2 || user.status == 4) {
          this.$store.dispatch('yyyyyy/yyyyyy').then(flag => {
            if (flag) {
              this.$router.push({
                path: '/logicPage_B',
                query: { xxxxx: xxx yyyyy: yyy }
              })
            } else {
              this.$router.push({
                path: '/logicPage_C',
                query: { xxxxx: xxx, yyyyy: yyy }
              })
            }
          })
        } else if (user.status == 3) {
          this.$router.push({
            path: '/logicPage_D',
            query: { xxxxx: xxx, yyyyy: yyy }
          })
        }
      })
    }
  }
}

2: vue文件 引入目标mixin文件

import someMixInFile from '@/mixin/someMixInFile'
export default {
  name: 'yourVueName',
  mixins: [someMixInFile],
  methods: {
    handleForward() {
      // 这里就可以调用混入进来的方法了.
      this.handleToLink(params)
  }
}

大量的节省代码,方便调试和修改.

转载于:https://www.jianshu.com/p/8af1e7c30983

猜你喜欢

转载自blog.csdn.net/weixin_33849215/article/details/91062689