Home > Article > Backend Development > How to display vue in golang
In recent years, with the development of front-end frameworks, many back-end languages have begun to try to combine with front-end frameworks to achieve full-stack development. Among these back-end languages, Go (Golang) has received more and more attention due to its efficiency, simplicity, stability and reliability. Vue.js is a fast front-end framework that provides many powerful tools and components, allowing developers to build complex single-page applications faster and easier.
In this article, we will explore how to embed Vue.js into a Golang web application to demonstrate the use of the front-end.
Before displaying Vue.js, you need to have the following technologies and tools:
npm install -g vue-cli
First, we need to create a Vue.js application. A standard Vue.js project can be quickly created using the Vue CLI:
vue init webpack-simple my-vue-app
Here, we have created a Vue.js project named my-vue-app
. This will create a project directory containing the Vue.js file.
Enter the my-vue-app
directory and run the following command:
npm install npm run dev
This will start a local web server and display Vue.js in the browser by default page.
Now we have created the Vue.js application and can run it locally. The next step is to embed it into our Go application.
The most common way to use Vue.js in a Go application is to place the Vue.js build files in a static directory in the Go application and reference these files in the HTML file. This can be achieved in the following two ways:
In this method we will use the HTML template provided by the Go application and Reference the Vue.js build file in it. We first need to ensure that the Vue.js build file has been compiled. We can use the following command to complete the compilation:
npm run build
Executing this command will create a directory named dist
, which contains our package After the Vue.js application. Now we need to move this directory to a static directory in our Go application. The static directory can be any directory we want, and it will store the static resource files in the application. In this article, we use static
as the static directory, you can modify it yourself.
Copy the dist
directory to the static directory of the Go application:
cp -r dist/ $GOPATH/src/my-app/static/
In our Go application, we need to define a http.FileServer
Handler, which will return the files in the static directory. We also need to define the template that will load the HTML file of the Vue.js application and include the Vue.js build file within it.
The following is the sample code for defining routes and templates:
package main import ( "html/template" "net/http" ) func main() { http.HandleFunc("/", handler) http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static")))) http.ListenAndServe(":8080", nil) } func handler(w http.ResponseWriter, r *http.Request) { tpl, err := template.ParseFiles("templates/index.html") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } err = tpl.Execute(w, nil) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) } }
In the above code, we define a route /
which will be displayed in the browser Open the templates/index.html
file and present it to the user. We also define a static file handler that will load files from our static directory. This handler will handle all requests starting with /static/
.
In our HTML template, we include the Vue.js build file and use the div#app
element as the root element of the Vue.js application.
The following is an example of an index.html
file:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>My Vue App</title> </head> <body> <div id="app"> <!-- Vue.js应用程序将在此渲染 --> </div> <script src="/static/js/app.js"></script> </body> </html>
In the above code, we set the path to the Vue.js build file to / static/js/app.js
. You can modify it yourself according to your needs.
In this method we will use Vue.js as our router and embed it into our Go in the application. This way, we will actually use the Go application as a backend for Vue.js, and Vue.js will be responsible for handling the user's routing requests.
First, we need to ensure that the Vue.js application has been compiled. We can complete the compilation using the following command:
npm run build
Executing this command will create a file named dist
directory, which contains our packaged Vue.js application. Now, we need to move this directory into the static directory of our Go application. The static directory can be any directory we want, and it will store the static resource files in the application. In this article, we use static
as the static directory, you can modify it yourself.
Copy the dist
directory into the static directory of the Go application:
cp -r dist/ $GOPATH/src/my-app/static/
In our Go application, we need to define a route handler that will Return the HTML file of the Vue.js application and let the Vue.js application call the API provided by our Go backend.
The following is sample code for defining routes and APIs:
package main import ( "encoding/json" "net/http" ) type Message struct { Text string `json:"text"` } func main() { http.HandleFunc("/", handler) http.HandleFunc("/api/hello", hello) http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static")))) http.ListenAndServe(":8080", nil) } func handler(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "index.html") } func hello(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") message := Message{"Hello, Vue.js!"} json.NewEncoder(w).Encode(message) }
在上面的代码中,我们定义了两个路由:/
和/api/hello
。/
路由将返回Vue.js应用程序的HTML文件,并让Vue.js应用程序调用我们的Go后端提供的API。/api/hello
路由是我们定义的API,它将返回一条简单的JSON消息。
在我们的Vue.js应用程序中,我们需要实现路由器,并确保它可以调用我们Go后端提供的API。以下是一个示例路由器:
import Vue from 'vue' import Router from 'vue-router' import HelloWorld from '@/components/HelloWorld' Vue.use(Router) export default new Router({ mode: 'history', routes: [ { path: '/', name: 'HelloWorld', component: HelloWorld } ] })
在上面的代码中,我们定义了一个路由器,并将/
路由与一个名为HelloWorld
的组件相对应。我们还将路由模式设置为history
,以便它使用HTML5路由历史记录API,并将其与我们的Go应用程序进行集成。
最后,在我们的Vue.js应用程序中,我们可以使用axios
来调用我们Go后端提供的API。以下是一个使用axios
调用API的示例:
<template> <div> <h1>{{ message }}</h1> </div> </template> <script> import axios from 'axios' export default { data () { return { message: '' } }, created () { axios.get('/api/hello') .then(response => { this.message = response.data.text }) .catch(error => { console.log(error) }) } } </script>
在上面的代码中,我们在组件的created
生命周期中使用axios
来调用我们的Go后端提供的API,并将响应数据设置为组件模板中的message
数据。
通过本文,我们已经学习了如何将Vue.js嵌入到Golang的Web应用程序中。我们已经探讨了两种方法,一种是使用模板,另一种是使用Vue.js路由器。通过使用Vue.js,我们可以更轻松地构建和管理复杂的前端应用程序,并将其与Golang开发的后端应用程序结合在一起。希望这篇文章可以帮助您更好地理解如何将Golang和Vue.js结合在一起,从而构建高效和可靠的全栈Web应用程序。
The above is the detailed content of How to display vue in golang. For more information, please follow other related articles on the PHP Chinese website!