[Vue] import custom external js

Posted by Jiraiya on Fri, 10 Jan 2020 17:43:29 +0100

1. Define js file, which is put under js file under static

The code is as follows:

// Judgement authority
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;
}

// Bullet box prompt
function tips(this_, message_, type_){
  this_.$message({
    message: message_,
    type: type_
  });
}

export { //Very critical
  hasPermissionJs,
  tips,
}

2. You can use it by importing it in the script tab of the interface

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

For example, when performing delete operation, call tips, the code is as follows:

    deleteAction(content, arr) {
      this.$confirm(content, 'Tips', {
          confirmButtonText: 'Determine',
          cancelButtonText: 'cancel',
          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, 'Illegal operation, unable to delete admin User!', 'error');
                return;
              }
              if(response.data.data == 'deleteYourself'){
                tips(this, 'Illegal operation, cannot delete yourself!', 'error');
                return;
              }
              tips(this, 'Delete successfully!', 'success');
              this.findPagesByCondition();
            })
        }).catch(() =>{
          // cancel
        });
    }

3. Precautions

① The export in js file must be written!!!

② If the introduced method is to be called when the DOM is loaded, for example, there are delete, edit and other operation buttons in the user list page. The code is as follows according to whether the permission is displayed or not:

<el-table-column label="operation">
      <template slot-scope="scope">
        <el-button @click="deleteUser(scope.row)" type="text" v-if="hasPermission('user:delete')">delete</el-button>
        <el-button @click="userForm(scope.row)" type="text" v-if="hasPermission('user:edit')">edit</el-button>
        <el-button @click="userVersionForm(scope.row)" type="text" v-if="hasPermission('user:dataAssign')">Assign data permissions</el-button>
      </template>
</el-table-column>

In this case, you need to write in methods to determine permissions when the page is loaded:

methods: {
    // Judgement authority
    hasPermission: hasPermissionJs,
    
    }

 

Topics: JSON