Vue.js RuoYiフレームワークの一般的な問題と解決策

問題1:現在のユーザー情報の取得

現在のユーザーIDやその他の情報を取得する方法

authStore.js

import { authenticate, deauthenticate, fetchUserData } from '@/api/auth'
import { getAuthToken, setAuthToken, removeAuthToken } from '@/utils/auth'

const auth = {
  state: {
    authToken: getAuthToken(),
    userId: '',
    username: '',
    profileImage: '',
    userRoles: [],
    userPermissions: [], 
    stores: [] // 店舗リスト
  },

  mutations: {
    UPDATE_AUTH_TOKEN: (state, token) => {
      state.authToken = token
    },
    UPDATE_USER_ID: (state, id) => {
      state.userId = id
    },
    UPDATE_USERNAME: (state, name) => {
      state.username = name
    },
    UPDATE_PROFILE_IMAGE: (state, image) => {
      state.profileImage = image
    },
    UPDATE_USER_ROLES: (state, roles) => {
      state.userRoles = roles
    },
    UPDATE_USER_PERMISSIONS: (state, permissions) => {
      state.userPermissions = permissions
    },
    UPDATE_STORES: (state, stores) => {
      state.stores = stores
    },
  },

  actions: {
    // ログイン処理
    AuthenticateUser({ commit }, credentials) {
      const username = credentials.username.trim()
      const password = credentials.password
      const verificationCode = credentials.code
      const sessionId = credentials.uuid
      return new Promise((resolve, reject) => {
        authenticate(username, password, verificationCode, sessionId).then(response => {
          setAuthToken(response.token)
          commit('UPDATE_AUTH_TOKEN', response.token)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // ユーザー情報取得
    FetchUserData({ commit, state }) {
      return new Promise((resolve, reject) => {
        fetchUserData().then(response => {
          const userData = response.user
          const storeData = response.stores
          const profileImage = (userData.avatar == "" || userData.avatar == null) ? require("@/assets/images/default-profile.jpg") : process.env.VUE_APP_BASE_API + userData.avatar;
          if (response.roles && response.roles.length > 0) { // 返されたrolesが空でない配列かどうかを検証
            commit('UPDATE_USER_ROLES', response.roles)
            commit('UPDATE_USER_PERMISSIONS', response.permissions)
          } else {
            commit('UPDATE_USER_ROLES', ['ROLE_DEFAULT'])
          }
          commit('UPDATE_USER_ID', userData.userId)
          commit('UPDATE_USERNAME', userData.userName)
          commit('UPDATE_PROFILE_IMAGE', profileImage)
          // 店舗情報を設定
          commit('UPDATE_STORES', storeData)
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },

    // システムからログアウト
    DeauthenticateUser({ commit, state }) {
      return new Promise((resolve, reject) => {
        deauthenticate(state.authToken).then(() => {
          commit('UPDATE_AUTH_TOKEN', '')
          commit('UPDATE_USER_ROLES', [])
          commit('UPDATE_USER_PERMISSIONS', [])
          // 店舗情報をクリア
          commit('UPDATE_STORES', [])
          removeAuthToken()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },

    // フロントエンドのみのログアウト
    FrontendLogout({ commit }) {
      return new Promise(resolve => {
        commit('UPDATE_AUTH_TOKEN', '')
        removeAuthToken()
        resolve()
      })
    }
  }
}

export default auth

stateGetters.js

const stateGetters = {
  sidebar: state => state.app.sidebar,
  size: state => state.app.size,
  device: state => state.app.device,
  dictionary: state => state.dictionary.data,
  visitedViews: state => state.tagsView.visitedViews,
  cachedViews: state => state.tagsView.cachedViews,
  authToken: state => state.auth.authToken,
  profileImage: state => state.auth.profileImage,
  username: state => state.auth.username,
  bio: state => state.auth.bio,
  userRoles: state => state.auth.userRoles,
  userPermissions: state => state.auth.userPermissions,
  stores: state => state.auth.stores, // 店舗情報
  permission_routes: state => state.permission.routes,
  topbarRouters:state => state.permission.topbarRouters,
  defaultRoutes:state => state.permission.defaultRoutes,
  sidebarRouters:state => state.permission.sidebarRouters,
}
export default stateGetters


問題2:RuoYiアプリケーションのNginx設定

worker_processes  1;

events {
    worker_connections  1024;
}

http {
    include       mime.types;
    default_type  application/octet-stream;
    sendfile        on;
    keepalive_timeout  65;

    server {
        listen    80;
        server_name  127.0.0.1;
		charset utf-8;

        location / {
            root   /var/www/frontend/dist;
            try_files $uri $uri/ /index.html;
            index  index.html index.htm;
        }
		
		location /api/ {
			proxy_set_header Host $http_host;
			proxy_set_header X-Real-IP $remote_addr;
			proxy_set_header REMOTE-HOST $remote_addr;
			proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
			proxy_pass http://localhost:8080/;
		}

        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }
    }
}


問題3:ページネーション付きの複数選択テーブル

<template>
  <div>
    <!-- ボタングループ -->
    <el-row :gutter="10" class="mb8">
      <el-button @click="clearSelection()">選択を解除</el-button>
    </el-row>
    <el-table
      ref="dataTable"
      :row-key="getRowIdentifier"
      v-loading="isLoading"
      :data="tableData"
      @selection-change="onSelectionChange"
      :header-cell-style="{ 'text-align': 'center' }"
      :cell-style="{ 'text-align': 'center' }"
    >
      <el-table-column type="selection" :reserve-selection="true" width="55" />
      <el-table-column label="番号" fixed>
        <template #default="scope">
          <span>{{
            (paginationParams.currentPage - 1) * paginationParams.pageSize + scope.$index + 1
          }}</span>
        </template>
      </el-table-column>
      <el-table-column property="name" label="名称" />
      <el-table-column property="date" label="日付" />
      <el-table-column property="address" label="住所" />
    </el-table>

    <pagination
      v-show="totalCount > 0"
      :total="totalCount"
      :page.sync="paginationParams.currentPage"
      :limit.sync="paginationParams.pageSize"
      @pagination="fetchData"
    />
  </div>
</template>
<script>
export default {
  name: "MultiSelectTable",
  data() {
    return {
      // ページネーションパラメータ
      paginationParams: {
        currentPage: 1,
        pageSize: 10,
      },
      // ローディング状態
      isLoading: false,
      // テーブルデータ
      tableData: [],
      // 総件数
      totalCount: 0,
      // サンプルデータ
      sampleData: [
        {
          id: 1,
          date: "2023-01-15",
          name: "田中太郎",
          address: "東京都新宿区1-2-3",
        },
        {
          id: 2,
          date: "2023-02-20",
          name: "佐藤花子",
          address: "東京都渋谷区4-5-6",
        },
        {
          id: 3,
          date: "2023-03-25",
          name: "鈴木一郎",
          address: "東京都品川区7-8-9",
        },
        {
          id: 4,
          date: "2023-04-10",
          name: "高橋次郎",
          address: "東京都港区10-11-12",
        },
        {
          id: 5,
          date: "2023-05-05",
          name: "伊藤三郎",
          address: "東京都中央区13-14-15",
        },
        {
          id: 6,
          date: "2023-06-18",
          name: "渡辺四郎",
          address: "東京都千代田区16-17-18",
        },
        {
          id: 7,
          date: "2023-07-22",
          name: "山田五郎",
          address: "東京都台東区19-20-21",
        },
        {
          id: 8,
          date: "2023-08-30",
          name: "中村六郎",
          address: "東京都墨田区22-23-24",
        },
        {
          id: 9,
          date: "2023-09-12",
          name: "小林七郎",
          address: "東京都江東区25-26-27",
        },
        {
          id: 10,
          date: "2023-10-08",
          name: "加藤八郎",
          address: "東京都荒川区28-29-30",
        },
        {
          id: 11,
          date: "2023-11-14",
          name: "吉田九郎",
          address: "東京都足立区31-32-33",
        },
        {
          id: 12,
          date: "2023-12-03",
          name: "山本十郎",
          address: "東京都葛飾区34-35-36",
        },
      ],
      // 選択された項目
      selectedIds: [],
    };
  },
  mounted() {
    this.fetchData();
  },
  methods: {
    // 行の一意の識別子を取得
    getRowIdentifier(row) {
      return row.id;
    },
    // ページネーションでデータを取得
    fetchData() {
      this.isLoading = true;
      this.tableData = JSON.parse(JSON.stringify(this.sampleData)).splice(
        (this.paginationParams.currentPage - 1) * this.paginationParams.pageSize,
        this.paginationParams.pageSize
      );
      this.totalCount = this.sampleData.length;
      this.isLoading = false;
    },

    // 選択変更時の処理
    onSelectionChange(selection) {
      this.selectedIds = selection.map((item) => item.id);
    },

    // 選択をクリア
    clearSelection(rows) {
      if (rows) {
        rows.forEach((row) => {
          this.$refs.dataTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.dataTable.clearSelection();
      }
    },
  },
};
</script>

タグ: vue.js RuoYi nginx ユーザー認証 ページネーション

6月14日 20:51 投稿