Self cultivation of the whole stack: 002 using @ vue/cli vue.js Environment construction

Posted by haddydaddy on Mon, 29 Jun 2020 09:27:29 +0200

<h1>Self cultivation of the whole stack: using @ vue/cli vue.js Environment construction</h1>

Success, real success, is being willing to do the things that other people are not.

Success, real success, is willing to do what others don't want to do.

Table of Contents

@[TOC]

When you read this article, I think you are interested in how to build a website

preface

The last article described the use of Vue cli to build Epimetheus frontend. It is true in some old projects, but the front-end framework release is just like taking a rocket 🚀 Just like that, I'm here to introduce the use of @ vue/cli

Vue CLI is a Vue.js A complete system for rapid development, providing:

  • The interactive project scaffolding realized by @ vue/cli.
  • Zero configuration prototype development is realized by @ Vue / cli + @ Vue / cli service global.
  • A runtime dependency (@ Vue / cli service) that:

    • Upgradeable;
    • It is based on webpack with reasonable default configuration;
    • It can be configured through the configuration file in the project;
    • It can be extended through plug-ins.
  • A rich collection of official plug-ins integrates the best tools in the front-end ecosystem.
  • A set of fully graphical creation and management Vue.js User interface for the project.

Vue CLI is committed to standardizing the tool base in the Vue ecosystem. It ensures that the various build tools work smoothly with intelligent default configurations, so you can focus on writing applications without having to spend days struggling with configuration issues. At the same time, it also provides flexibility for each tool to adjust the configuration without eject.

The introduction of Vue CLI comes from the official website, and there is a corresponding reference address at the end of the article

Delete code without running

Deleting code, as a programmer, should be a very physical and mental pleasure

In the previous document, we have created Epimetheus frontend using the old version of Vue cli. First, we deleted him

epimetheus$ rm -rf epimetheus-frontend

Because both the new and old versions of vue cli use the vue command, you need to uninstall the last installed vue cli at this time

epimetheus$ npm uninstall vue-cli -g

So we have a clean environment again

Node version requirements < br / > < br / >
Vue CLI requires Node.js 8.9 or later (8.11.0 + is recommended).

Install @ vue/cli

In the first part, we used NPM install - G Vue cli to complete the installation of Vue cli

As a new version, the package name of Vue CLI has been changed from Vue CLI to @ vue/cli. We need to execute the following command to install

epimetheus$ npm install -g @vue/cli

The installation speed is still relatively slow. You can drink a glass of water

After installation, you can view the version number in vue --version

epimetheus$ vue --version
@vue/cli 4.4.6

Create a Vue project

Here we continue to create Epimetheus frontend

  1. Let's go to the epimetheus directory we created last time
  2. Execute Vue create Epimetheus frontend to create the project

In the first step, you will be prompted to select a preset, where the default Babel + eslint < br / > is selected
In the second step, you will be prompted to select package manager. Here, we will still choose Yarn

The installation process may be a little slow. After the installation is completed, it is as follows

epimetheus$ vue create epimetheus-frontend


Vue CLI v4.4.6
? Please pick a preset: default (babel, eslint)
? Pick the package manager to use when installing dependencies: Yarn


Vue CLI v4.4.6
✨  Creating project in /Users/zhangyunan/project/scoding/epimetheus/epimetheus-frontend.
🗃  Initializing git repository...
⚙️  Installing CLI plugins. This might take a while...

yarn install v1.15.2
info No lockfile found.
[1/4] 🔍  Resolving packages...



success Saved lockfile.
info To upgrade, run the following command:
$ curl --compressed -o- -L https://yarnpkg.com/install.sh | bash
✨  Done in 30.95s.
🚀  Invoking generators...
📦  Installing additional dependencies...

yarn install v1.15.2
[1/4] 🔍  Resolving packages...
[2/4] 🚚  Fetching packages...
[3/4] 🔗  Linking dependencies...
[4/4] 🔨  Building fresh packages...

success Saved lockfile.
✨  Done in 5.79s.
⚓  Running completion hooks...

📄  Generating README.md...

🎉  Successfully created project epimetheus-frontend.
👉  Get started with the following commands:

 $ cd epimetheus-frontend
 $ yarn serve

From the above prompt, we can see that a git project is created by default

According to the final prompt, we can enter Epimetheus frontend and run yarn serve on the console to start running our project

epimetheus$ cd epimetheus-frontend
epimetheus/epimetheus-frontend$ (master) yarn serve
yarn run v1.15.2
$ vue-cli-service serve
 INFO  Starting development server...
98% after emitting CopyPlugin

 DONE  Compiled successfully in 2275ms                                                         10 pm:13:29


  App running at:
  - Local:   http://localhost:8080/
  - Network: http://192.168.1.4:8080/

  Note that the development build is not optimized.
  To create a production build, run yarn build.

From the console information, we can see that the access path is: http://localhost:8080

In this way, the preparatory work is basically completed

Project structure

I believe that the development of the previous document, you can use the code command, if you still can't use, you can install according to the following tips, here we directly use code. Open the current directory

For example:

epimetheus/epimetheus-frontend$  code .

The current folder Epimetheus / Epimetheus frontend will be opened in VSCode,

After installing VSCode, when you use the code command, you will be prompted not fund. You can enter code in the view - command panel to install

[the transfer of the external chain image failed. The source station may have anti-theft chain mechanism, so it is recommended to save the picture and upload it directly (img-jvkcj2uz-1593393770883) (IMG / vscode)_ install_ code.png ]

VSCode is used here. After opening the project, it is shown as follows:

├── README.md                 # Default README file
├── babel.config.js
├── package.json              # build scripts and dependencies
├── public
│   ├── favicon.ico
│   └── index.html            # index.html template
├── src
│   ├── App.vue               # main app component
│   ├── assets                # module assets
│   │   └── logo.png
│   ├── components
│   │   └── HelloWorld.vue
│   └── main.js               # app entry file
└── yarn.lock

vue-cli3.0 modify port number

Among them, we mainly modify the file under src. As mentioned above, the access port of the project is 8080. In order to prevent conflicts with other projects, we change the port to 7000, which provides two ways:

  1. package.json Modify under file -- port
"scripts": {
   "serve": "vue-cli-service serve --port 7000",
}
  1. In package.json Created under the same level vue.config.js , and add the following
module.exports = {
  devServer: {
    port: 7000
  }
}

Either way

Using elementUI

It's used here
Official website: http://element-cn.eleme.io/#/...

Here we go to the project directory: and execute the yarn add element UI

And configuration main.js

import Vue from 'vue'

import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';

import App from './App.vue'

Vue.use(ElementUI);

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
}).$mount('#app')

Installing Vuex

Vuex is a Vue.js State management mode of application development. It uses centralized storage to manage the state of all components of the application, and ensures that the state changes in a predictable way with corresponding rules. Vuex is also integrated into Vue's official debugging tool, devtools extension, which provides advanced debugging functions such as zero configuration time travel debugging, state snapshot import and export, etc.

In other words, through Vuex, each component can share the state in real time

Official website: https://vuex.vuejs.org/zh-cn/...

install

First of all, let's install the yarn add vuex

to configure

First create the store folder under src and create it under it store.js file
src/store/store.js , and create src/assets/util/cookie.js

src/assets/utils/cookie.js Document content

This file is mainly used to manipulate cookie s

let cookie = {
  setCookie (cname, value, expiredays) {
    let exdate = new Date()
    exdate.setTime(exdate.getTime() + expiredays)
    exdate.setDate(exdate.getDate() + expiredays) 
    document.cookie = cname + '=' + escape(value) + ((expiredays == null) ? '' : ';expires=' + exdate.toGMTString())
  },
  getCookie (name) {
    let reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)')
    let arr = document.cookie.match(reg)
    if (arr) {
      return (arr[2])
    } else {
      return null
    }
  },
  delCookie (name) {
    let exp = new Date()
    exp.setTime(exp.getTime() - 1)
    let cval = cookie.getCookie(name)
    if (cval != null) {
      document.cookie = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;'
    }
  }
}

export default cookie

src/store/store.js content

Here, userInfo is defined to save the current user information, including a name and token

import Vue from 'vue'
import Vuex from 'vuex'
import cookie from '../assets/utils/cookie'

Vue.use(Vuex)

const userInfo = {
  name: cookie.getCookie('name') || '',
  token: cookie.getCookie('token') || ''
}

const store = new Vuex.Store({
  state: {
    userInfo: userInfo
  },
  mutations: {
    setUserInfo (state) {
      state.userInfo = {
        name: cookie.getCookie('name'),
        token: cookie.getCookie('token'),
      }
    }
  }
})

export default store

In main.js Add Vuex configuration,

import Vue from 'vue'

import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import store from './store/store'

import App from './App.vue'

Vue.use(ElementUI);

Vue.config.productionTip = false

new Vue({
  store,
  render: h => h(App),
}).$mount('#app')

Installing axios

Promise based HTTP client for the browser and node.js

axios is a Promise based http client. Through it, we can interact with the back end data. If you don't like it, you can use jquery's ajax instead

Let's install yarn add axios

final main.js

import Vue from 'vue'

import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import store from './store/store'

import App from './App.vue'

Vue.use(ElementUI);

Vue.config.productionTip = false

new Vue({
  store,
  render: h => h(App),
}).$mount('#app')

github

https://github.com/zhangyunan...

reference resources

Topics: node.js Vue npm JSON axios