【Vue】引入自定义外部js

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Mr_EvanChen/article/details/81033172

1、定义js文件,这里是放在static下的js文件下

代码如下:


// 判断权限
function hasPermissionJs(val) {
  var restoredSession = JSON.parse(sessionStorage.getItem('userInfo'));
  var roles = restoredSession.user.roles;
  for(var i=0; i<roles.length; i++){
    for(var j=0; j<roles[i].authorities.length; j++){
      if(val == roles[i].authorities[j].mtag){
        return true;
      }
    }
  }
  if(restoredSession.isAdmin==true){
    return true;
  }
  return false;
}

// 弹框提示
function tips(this_, message_, type_){
  this_.$message({
    message: message_,
    type: type_
  });
}

export { //很关键
  hasPermissionJs,
  tips,
}

2、在界面的script标签中进行引入即可使用

<script>
import {hasPermissionJs, tips} from '../../static/js/my.js'
</script>

    例如执行删除操作时,调用tips,代码如下:

    deleteAction(content, arr) {
      this.$confirm(content, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var params = new URLSearchParams();
          params.append('uid', arr);
          this.$http.post("/api/v1/user/delete", params)
            .then(response => {
              if(response.data.data == 'deleteAdminUser'){
                tips(this, '非法操作,不能删除admin用户!', 'error');
                return;
              }
              if(response.data.data == 'deleteYourself'){
                tips(this, '非法操作,不能删除自己!', 'error');
                return;
              }
              tips(this, '删除成功!', 'success');
              this.findPagesByCondition();
            })
        }).catch(() =>{
          // 取消
        });
    }

3、注意事项

① js文件中的export必须要写!!!

② 如果引入的方法是要在DOM加载时就调用的,例如用户列表页面中,有删除、编辑等操作按钮,根据权限进行展示与否的判断,代码如下:

<el-table-column label="操作">
      <template slot-scope="scope">
        <el-button @click="deleteUser(scope.row)" type="text" v-if="hasPermission('user:delete')">删除</el-button>
        <el-button @click="userForm(scope.row)" type="text" v-if="hasPermission('user:edit')">编辑</el-button>
        <el-button @click="userVersionForm(scope.row)" type="text" v-if="hasPermission('user:dataAssign')">分配数据权限</el-button>
      </template>
</el-table-column>

那么此时需要在methods中这样写,就可以在页面加载时就判断权限:

methods: {
    // 判断权限
    hasPermission: hasPermissionJs,
    
    }

猜你喜欢

转载自blog.csdn.net/Mr_EvanChen/article/details/81033172