搜尋
首頁後端開發Golang如何使用Go語言和Vue.js建立使用者管理元件

如何使用Go語言和Vue.js建立使用者管理元件

Jun 17, 2023 am 11:18 AM
go語言vuejs使用者管理元件

隨著網路時代的不斷發展,越來越多的企業開始使用軟體來進行業務操作和管理。而擁有優秀用戶管理組件的軟體,能夠幫助企業更好地管理和維護用戶訊息,以及提供更好的用戶體驗。本文將介紹如何使用Go語言和Vue.js建立使用者管理元件,幫助讀者打造一款高效、易用的使用者管理工具。

一、設計使用者管理API

首先需要設計一個符合業務需求的使用者管理API介面。在本範例中,我們將定義API介面如下:

建立使用者:

POST /api/users

查詢使用者清單:

GET / api/users

查詢單一使用者:

GET /api/users/{id}

更新使用者:

PUT /api/users/{ id}

刪除使用者:

DELETE /api/users/{id}

把認證部分放在一個中間件裡,用JWT進行認證,例如:

middleware/auth.go

func AuthMiddleware(next http.Handler) http.Handler {
  return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
    // verify token
    tokenStr := r.Header.Get("Authorization")
    if tokenStr == "" {
        http.Error(w, "Authorization required", http.StatusUnauthorized)
        return
    }

    token, err := jwt.Parse(tokenStr, func(token *jwt.Token) (interface{}, error) {
        return []byte("Secret"), nil
    })

    if err != nil || !token.Valid {
        http.Error(w, "Invalid authorization token", http.StatusUnauthorized)
    }

    // Call the next handler, which can be another middleware in the chain, or the final handler.
    next.ServeHTTP(w, r)
})
}

2、寫後端服務

完成API設計後,需撰寫後端服務,提供對應API介面的實作。

使用Go語言編寫後端服務,我們可以使用一些流行的Web框架,如Gin、Echo或Goji。這裡我們使用Gin框架作為例子,範例程式碼如下:

backend/main.go

func main() {
router := gin.Default()

// Register middleware
router.Use(middleware.AuthMiddleware)

// Create user
router.POST("/api/users", CreateUser)

// Query user list
router.GET("/api/users", GetUserList)

// Query single user
router.GET("/api/users/:id", GetUser)

// Update user
router.PUT("/api/users/:id", UpdateUser)

// Delete user
router.DELETE("/api/users/:id", DeleteUser)

// Start server
router.Run(":8080")
}

以上程式碼中,AuthMiddleware用來認證路由請求,接著使用router.POST、router.GET 、router.PUT和router.DELETE方法註冊API路由並關聯實作函數CreateUser、GetUserList、GetUser、UpdateUser和DeleteUser。

3、寫前端介面元件

有了後端服務,我們就可以寫前端介面元件了。使用Vue.js建構前端元件,我們可以使用常用的建置工具,如webpack或vue-cli。這裡我們使用vue-cli,範例程式碼如下:

frontend/src/App.vue

<template>
    <div>
        <!-- User list component -->
        <user-list :users="users" @update="handleUpdate" @delete="handleDelete" />

        <!-- User form component -->
        <user-form v-if="showForm" :user="user" @submit="handleSubmit" @cancel="handleCancel" />
    
        <!-- Button to show user form component -->
        <el-button type="primary" @click="showForm = true">Create User</el-button>
    </div>
</template>

<script>
    import UserList from './components/UserList.vue'
    import UserForm from './components/UserForm.vue'
    import axios from 'axios'
    
    export default {
        components: {
            UserList,
            UserForm
        },

        data() {
            return {
                users: [],
                user: {},
                showForm: false
            }
        },

        methods: {
            // Get user list from backend API
            async loadUsers() {
                const response = await axios.get('/api/users')
                this.users = response.data
            },

            // Handle user update
            handleUpdate(user) {
                this.user = user
                this.showForm = true
            },

            // Handle user delete
            async handleDelete(userId) {
                await axios.delete(`/api/users/${userId}`)
                await this.loadUsers()
            },

            // Handle form submit
            async handleSubmit(user) {
                if (user.id) {
                    await axios.put(`/api/users/${user.id}`, user)
                } else {
                    await axios.post('/api/users', user)
                }
                
                this.showForm = false
                await this.loadUsers()
            },

            // Handle cancel button click
            handleCancel() {
                this.showForm = false
            }
        },

        created() {
            this.loadUsers()
        }
    }
</script>

以上程式碼中,App元件使用UserList、UserForm、axios庫和backend API互動實作功能。

UserList元件是一個表格元件,接收users屬性作為表格渲染資料。

UserForm组件用于创建和编辑userdata。如果用户信息为新用户数据, updateUser则设置为空对象,否则它设置为要编辑的用户。

async函数 handleSubmit处理与API的交互。如果用户存在,将其作为HTTP PUT请求发出,否则将其记录下来并存储到backend中。

任何操作導致此功能中資料的變更都會觸發UI重新載入。

到這裡,我們已經完成了使用Go語言和Vue.js建立使用者管理元件的開發工作。開發人員可以進一步改進和完善,根據實際業務需求,進行適當的修改和擴展,打造一款符合自己需求的使用者管理工具。

總結

本文介紹如何使用Go語言和Vue.js建立使用者管理元件。透過API設計與後端服務實現,實現了使用者資訊的CRUD操作,再透過Vue.js實現了使用者管理介面元件,讓使用者管理更為方便和有效率。同時,本文提供了範例程式碼和開發步驟,能夠幫助讀者更易入手此方面的開發工作。

以上是如何使用Go語言和Vue.js建立使用者管理元件的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
使用GO編程語言構建可擴展系統使用GO編程語言構建可擴展系統Apr 25, 2025 am 12:19 AM

goisidealforbuildingscalablesystemsduetoitssimplicity,效率和建築物內currencysupport.1)go'scleansyntaxandaxandaxandaxandMinimalisticDesignenhanceProductivityAndRedCoductivityAndRedCuceErr.2)ItSgoroutinesAndInesAndInesAndInesAndineSandChannelsEnablenableNablenableNableNablenableFifficConcurrentscorncurrentprogragrammentworking torkermenticmminging

有效地使用Init功能的最佳實踐有效地使用Init功能的最佳實踐Apr 25, 2025 am 12:18 AM

Initfunctionsingorunautomationbeforemain()andareusefulforsettingupenvorments和InitializingVariables.usethemforsimpletasks,避免使用輔助效果,andbecautiouswithTestingTestingTestingAndLoggingTomaintAnainCodeCodeCodeClarityAndTestesto。

INIT函數在GO軟件包中的執行順序INIT函數在GO軟件包中的執行順序Apr 25, 2025 am 12:14 AM

goinitializespackagesintheordertheordertheyimported,thenexecutesInitFunctionswithinApcageIntheirdeFinityOrder,andfilenamesdetermineTheOrderAcractacractacrosmultiplefiles.thisprocessCanbeCanbeinepessCanbeInfleccessByendercrededBydeccredByDependenciesbetenciesbetencemendencenciesbetnependendpackages,whermayleLeadtocomplexinitialitialializizesizization

在GO中定義和使用自定義接口在GO中定義和使用自定義接口Apr 25, 2025 am 12:09 AM

CustomInterfacesingoarecrucialforwritingFlexible,可維護,andTestableCode.TheyEnableDevelostOverostOcusonBehaviorBeiroveration,增強ModularityAndRobustness.byDefiningMethodSigntulSignatulSigntulSignTypaterSignTyperesthattypesmustemmustemmustemmustemplement,InterfaceSallowForCodeRepodEreusaperia

在GO中使用接口進行模擬和測試在GO中使用接口進行模擬和測試Apr 25, 2025 am 12:07 AM

使用接口進行模擬和測試的原因是:接口允許定義合同而不指定實現方式,使得測試更加隔離和易於維護。 1)接口的隱式實現使創建模擬對像變得簡單,這些對像在測試中可以替代真實實現。 2)使用接口可以輕鬆地在單元測試中替換服務的真實實現,降低測試複雜性和時間。 3)接口提供的靈活性使得可以為不同測試用例更改模擬行為。 4)接口有助於從一開始就設計可測試的代碼,提高代碼的模塊化和可維護性。

在GO中使用init進行包裝初始化在GO中使用init進行包裝初始化Apr 24, 2025 pm 06:25 PM

在Go中,init函數用於包初始化。 1)init函數在包初始化時自動調用,適用於初始化全局變量、設置連接和加載配置文件。 2)可以有多個init函數,按文件順序執行。 3)使用時需考慮執行順序、測試難度和性能影響。 4)建議減少副作用、使用依賴注入和延遲初始化以優化init函數的使用。

GO的選擇語句:多路復用並發操作GO的選擇語句:多路復用並發操作Apr 24, 2025 pm 05:21 PM

go'SselectStatementTreamLinesConcurrentProgrambyMultiplexingOperations.1)itallowSwaitingOnMultipleChannEloperations,執行thefirstreadyone.2)theDefirstreadyone.2)thedefefcasepreventlocksbysbysbysbysbysbythoplocktrograpraproxrograpraprocrecrecectefnoopeready.3)

GO中的高級並發技術:上下文和候補組GO中的高級並發技術:上下文和候補組Apr 24, 2025 pm 05:09 PM

contextancandwaitgroupsarecrucialingoformanaginggoroutineseflect.1)context contextsallowsAllowsAllowsAllowsAllowsAllingCancellationAndDeadLinesAcrossapibiboundaries,確保GoroutinesCanbestoppedGrace.2)WaitGroupsSynChronizeGoroutines,確保Allimizegoroutines,確保AllizeNizeGoROutines,確保AllimizeGoroutines

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。