Vue 使用mixin抽取共通方法

引入原因:

  • 当一段逻辑在不同的地方使用时

step-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 }
          })
        }
      })
    }
  }
}

step-2: vue文件 引入mixin文件

import someMixInFile from '@/mixin/someMixInFile'
export default {
  name: 'yourVueName',
  mixins: [someMixInFile],
  methods: {
    handleForward() {
      // 这里就可以调用混入进来的方法了.
      this.handleToLink(params)
  }
}
posted @ 2020-07-23 09:55  荣光无限  阅读(378)  评论(0编辑  收藏  举报