Home Backend Development Golang How to build reusable modal components using Go language and Vue.js

How to build reusable modal components using Go language and Vue.js

Jun 17, 2023 pm 11:18 PM
go language vuejs Reusable modal box

With the continuous development of web applications, modal boxes have become an indispensable part of web design. A modal is a pop-up window used to display information or collect data when the user interacts with an application. In this article, we will introduce how to build reusable modal components using Go language and Vue.js.

Go language is an efficient, reliable and easy-to-assemble programming language developed by Google. Vue.js is a lightweight JavaScript framework that focuses on building user interfaces. Use Go language and Vue.js together to create efficient web applications. In this article, we’ll show you how to use these two tools to build reusable modal components.

Before starting this tutorial, you need to have the following prerequisites:

  • Some basic knowledge of the Go language.
  • Be familiar with the Vue.js framework and its basic concepts.
  • A text editor, such as Visual Studio Code, etc.

We will build our modal component using Vue.js and Bootstrap. Please make sure you have installed the Vue.js and Bootstrap packages.

Step 1: Create a Vue.js component

First, we need to create a Vue.js component that contains a modal box. In your Vue.js application, create a new folder, say "components", and inside it create a file called "Modal.vue". Copy the following code:

<template>
  <div class="modal fade" tabindex="-1" role="dialog">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">{{title}}</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          <slot></slot>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">{{cancelText}}</button>
          <button type="button" class="btn btn-primary" @click="save">{{saveText}}</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  props: {
    title: String,
    cancelText: {
      type: String,
      default: 'Cancel'
    },
    saveText: {
      type: String,
      default: 'Save'
    }
  },
  methods: {
    save() {
      this.$emit('save');
    }
  }
}
</script>
Copy after login

This component has a title, body and buttons for saving or canceling the action. There is also a method called "save" on this component that emits an event when the user clicks the "Save" button.

Step 2: Create the modal box using Bootstrap

Next, we need to create the actual modal box using Bootstrap. Create a new file called "index.html" in your application and add the following HTML code in it:

<!DOCTYPE html>
<html>
  <head>
    <title>Vue Modal</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet">
  </head>
  <body>
    <div id="app">
      <modal ref="modal" :title="title" :cancel-text="cancelText" :save-text="saveText" @save="save"></modal>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/vue-bootstrap-modal"></script>
    <script>
      new Vue({
        el: '#app',
        components: {
          modal: VueBootstrapModal
        },
        data: {
          title: 'Modal Title',
          cancelText: 'Cancel',
          saveText: 'Save'
        },
        methods: {
          save() {
            alert('Save clicked');
          },
          showModal() {
            this.$refs.modal.$modal.show();
          }
        }
      });
    </script>
  </body>
</html>
Copy after login

This code introduces a Vue.js component containing a modal box to the application program and then created an actual modal using Bootstrap.

Step 3: Create a backend using Go language

Now, we need to create a backend API using Go language to interact with our modal box. We will create a new Go language folder, say "api", and create a file called "handler.go" in it. Copy the following code:

package api

import (
    "encoding/json"
    "net/http"
)

type modal struct {
    Title string `json:"title"`
}

func HandleModal(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")
    w.WriteHeader(http.StatusOK)

    switch r.Method {
    case http.MethodGet:
        getModal(w, r)
    case http.MethodPost:
        saveModal(w, r)
    default:
        w.WriteHeader(http.StatusNotFound)
    }
}

func getModal(w http.ResponseWriter, r *http.Request) {
    m := modal{
        Title: "Example Modal",
    }

    if err := json.NewEncoder(w).Encode(m); err != nil {
        w.WriteHeader(http.StatusInternalServerError)
        return
    }
}

func saveModal(w http.ResponseWriter, r *http.Request) {
    type requestData struct {
        Title string `json:"title"`
    }

    var data requestData
    if err := json.NewDecoder(r.Body).Decode(&data); err != nil {
        w.WriteHeader(http.StatusBadRequest)
        return
    }

    m := modal{
        Title: data.Title,
    }

    if err := json.NewEncoder(w).Encode(m); err != nil {
        w.WriteHeader(http.StatusInternalServerError)
        return
    }
}
Copy after login

This file defines a structure named "modal", which contains a title field of type String. There are also two functions called "getModal" and "saveModal" that are used to send GET and POST requests to return or save headers.

Step 4: Use Axios to send HTTP requests

Finally, we need to use the Axios library to send HTTP requests in the Vue.js application to interact with the Go backend. Add the following JavaScript code in the "index.html" file:

<script src="https://cdn.jsdelivr.net/npm/axios"></script>
<script>
  new Vue({
    el: '#app',
    components: {
      modal: VueBootstrapModal
    },
    data: {
      title: '',
      cancelText: 'Cancel',
      saveText: 'Save'
    },
    methods: {
      save() {
        axios.post('/api/modal', {
          title: this.title
        })
        .then((response) => {
          alert('Save clicked. Title: ' + response.data.title);
        })
        .catch((error) => {
          console.log(error);
        });
      },
      showModal() {
        axios.get('/api/modal')
        .then((response) => {
          this.title = response.data.title;
          this.$refs.modal.$modal.show();
        })
        .catch((error) => {
          console.log(error);
        });
      }
    }
  });
</script>
Copy after login

This code uses the Axios library to send POST and GET requests to interact with the Go backend and save or get the headers.

You have now completed the process of building a reusable modal box component using Go language and Vue.js. You can use this code as a reference to build your own modal components to meet your specific web design needs.

The above is the detailed content of How to build reusable modal components using Go language and Vue.js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

In Go, why does printing strings with Println and string() functions have different effects? In Go, why does printing strings with Println and string() functions have different effects? Apr 02, 2025 pm 02:03 PM

The difference between string printing in Go language: The difference in the effect of using Println and string() functions is in Go...

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

What is the difference between `var` and `type` keyword definition structure in Go language? What is the difference between `var` and `type` keyword definition structure in Go language? Apr 02, 2025 pm 12:57 PM

Two ways to define structures in Go language: the difference between var and type keywords. When defining structures, Go language often sees two different ways of writing: First...

When using sql.Open, why does not report an error when DSN passes empty? When using sql.Open, why does not report an error when DSN passes empty? Apr 02, 2025 pm 12:54 PM

When using sql.Open, why doesn’t the DSN report an error? In Go language, sql.Open...

See all articles