Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to build vue+vuex+koa2 development environment

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly introduces the relevant knowledge of how to build the vue+vuex+koa2 development environment, the content is detailed and easy to understand, the operation is simple and fast, and has a certain reference value. I believe you will gain something after reading this article on how to build the vue+vuex+koa2 development environment. Let's take a look at it.

Part one: environmental construction

Vue + vuex environment

The first is the vue + vue-router + vuex environment. We use vue-cli scaffolding to generate the project, and students who can use vue should be familiar with this piece.

/ / Global installation scaffolding tool npm I vue-vli-g vue-vli / verify whether the scaffolding tool is installed successfully vue--version// build project vue init webpack project name / / Test whether the vue project runs successfully npm run dev

Because the scaffolding generated vue project does not contain vuex, install vuex again.

/ / install vuexnpm i vuex-- save

Koa2 environment

Once the front-end project is built, we begin to build our back-end services.

First, create a new directory in your development tools (whether webstorm or sublime) to build koa-based web services.

Here, we might as well name this directory koa-demo.

Then execute:

/ / enter the directory cd koa-demo// to generate package.jsonnpm init-y koa-cors / install the following dependency npm i koanpm i koa-routernpm I koa-cors

After installing koa and two middleware, the environment is set up.

Part two: sample development

The environment is built for use, so let's write a demo right away.

Demo development is not only a process of practicing how to write code in a development environment, but also a process of verifying whether the environment is right and useful.

Back-end interface development

In this case, the back end provides only one service, that is, an interface to the front end that returns json data. The code contains comments, so go directly to the code.

Server.js file

/ / server.js file let Koa = require ('koa'); let Router = require (' koa-router'); let cors = require ('koa-cors'); / / File system introduced into modejs APIlet fs = require (' fs'); const app = new Koa (); const router = new Router (); / / provide a / getJson interface router. Get ('/ getJson', async ctx = > {/ / the backend allows cors to request await cors across domains / / data returned to the front end ctx.body = JSON.parse (fs.readFileSync ('. / static/material.json'));}); / / connect koa with two middleware app.use (router.routes ()) .use (router.allowedMethods ()); / / listen on port 3000 app.listen (3000)

This uses a json file, in the'. / static/material.json' path, the code of the json file is:

/ material.json file [{"id": 1, "date": "2016-05-02", "name": "Zhang San", "address": "Beijing Tsinghua University",}, {"id": 2, "date": "2016-05-04", "name": "Li Si", "address": "Shanghai Fudan University",}, {"id": 3 "date": "2016-05-01", "name": "Wang Wu", "address": "Guangdong Sun Yat-sen University",}, {"id": 4, "date": "2016-05-03", "name": "Zhao Liu", "address": "Guangdong Shenzhen University",}, {"id": 5, "date": "2016-05-05", "name": "Han Meimei" "address": "Sichuan University",}, {"id": 6, "date": "2016-05-11", "name": "Liu Xiaolu", "address": "Hunan Central South University",}, {"id": 7, "date": "2016-04-13", "name": "Zeng Tan", "address": "Nanjing University in Jiangsu",}]

Then we start the service with the following command

Node server.js

Test whether the interface is good

Open a browser and enter http://127.0.0.1:3000/getJson. Take a look at whether the json data in the json file is displayed on the page. If it can be displayed, it means that the service that provides json data has been built.

Example of a front-end calling back-end interface

In order to highlight the key points, eliminate interference and facilitate understanding. Our front end writes a component, which has two parts: first, a button that invokes the getJson interface of the web service, and then a content display area. After getting the data returned by the back end, it is displayed in this area of the component.

First of all, let's look at the component file.

Fetch json {{json}} import {store} from'. / vuex' export default {computed: {json () {return store.state.json;}}, methods: {getJson () {store.dispatch ("getJson");}} .showJson {width:500px; margin:10px auto; min-height:500px; background-color: palegreen;} from the backend

It's very simple, so I don't have to explain much.

Then look at our vuex file.

Import Vue from 'vue'import Vuex from' vuex';Vue.use (Vuex) const state = {json: [],}; const mutations = {setJson (state, db) {state.json = db }} const actions = {getJson (context) {/ / call our backend getJson interface fetch ('http://127.0.0.1:3000/json', {method:' GET', / / mode:'cors', headers: {'Accept':' application/json', 'Content-Type':' application/json',} Function (res) {if (res.status = 200) {return res.json ()}) .then (function (json) {/ / console.log (typeof Array.from (json), Array.from (json)) Context.commit ('setJson', Array.from (json));})}; export const store = new Vuex.Store ({state: state, mutations: mutations, actions: actions,})

Ok, the code is done.

Talk about axios.

If you want to change the fetch of this demo to axios, the work to be done is as follows:

1. Install axios and reference axios in vuex file

Npm i axiosimport axios from 'axios'

2. Replace part of the fetch code with:

Const actions = {getJson (context) {axios.get ('/ json', {method: 'GET', / / mode:'cors', headers: {' Accept': 'application/json',' Content-Type': 'application/json',} }) .then (function (res) {if (res.status = 200) {return res.data}) .then (function (json) {/ / console.log (typeof Array.from (json), Array.from (json)) Context.commit ('setJson', Array.from (json));})}}

3. You will encounter the configuration of cross-domain, modify it in webpack, and add proxyTable entry to the path config/index.js file:

ProxyTable: {'/ json': {target: 'http://127.0.0.1:3000', changeOrigin: true, pathRewrite: {' ^ / json':'/ json'}, this is the end of this article on how to build a vue+vuex+koa2 development environment. Thank you for reading! I believe you all have a certain understanding of "how to build a vue+vuex+koa2 development environment". If you want to learn more, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report