Vue2.0 Beginner's Guide — From Environment Setup to Deployment
Category Programming Technology
>
Jinkey Original showonne, yubang Technical Guidance Demo Address:http://demo.jinkey.io/vue2Source Code:https://github.com/Jinkeycode/vue2-example
Vue2 Tutorial: https://www.tutorialpro.org/vue2/vue-tutorial.html
What is Vue
Vue is a front-end framework with the feature of data binding
>
For example, changing the value of an input field will automatically synchronize and update the values of other components bound to that input field.
Componentization
>
Even the smallest button on a page can be a separate .vue file, and these small components can be assembled like Lego blocks by referencing each other.
Recommended Development Environment for Vue2.0
Homebrew 1.0.6(Mac), Node.js 6.7.0, npm 3.10.3, webpack 1.13.2, vue-cli 2.4.0, Atom 1.10.2
Environment Installation
Installing brew on Mac OS
Open the terminal and run the following command:
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
Installing nodejs on Mac OS
brew install nodejs
Updating npm version with npm install [email protected] results in an error:
>
(node:42) fs: re-evaluating native module sources is not supported.
Solution:
>
- It seems that the installation package from the official website did not automatically configure environment variables in the past. Since I had previously installed nodejs on my computer, the environment variables were already configured, and I'm not sure if the current installation package does this automatically.
For Windows, simply download the installation package.
For Linux, you can use apt-get (ubuntu) or yum (centos) commands to install.
For details, refer to: http://www.tutorialpro.org/nodejs/nodejs-install-setup.html
Granting access permissions to the nodejs module installation directory
sudo chmod -R 777 /usr/local/lib/node_modules/
Installing the Taobao mirror
As everyone knows, using the official npm mirror directly in China is very slow, so it is recommended to use the Taobao NPM mirror.
npm install -g cnpm --registry=https://registry.npmmirror.com
This allows you to use the cnpm command to install modules:
cnpm install [name]
Installing webpack
cnpm install webpack -g
Installing the vue scaffolding
npm install vue-cli -g
Find a folder on your hard drive to store the project, and enter the directory in the terminal
cd directory path
Create a project based on a template
>
vue init webpack-simple project-name<project name cannot be in Chinese>
There will be some initial setup, as follows: Target directory exists. Continue? (Y/n)
Press Enter directly (then it will download the vue2.0 template, which may require a proxy connection) Project name (vue-test)
Press Enter directly Project description (A Vue.js project)
Press Enter directly Author
Write your own name
Use the cd command to enter the project directory
The project directory looks like this:
Installing Project Dependencies
Be sure to install from the official repository; the npm server is abroad, so this step will be slow.
npm install
Do not install from the domestic mirror cnpm (this will result in missing many dependency libraries)
cnpm install
Installing the vue-router and vue-resource modules
cnpm install vue-router vue-resource --save
Starting the project
npm run dev
Filling in the gaps (the following issues may be due to vue2.0 causing other related compilation and packaging tools not being updated)
>
【Key Point】Later, it was found that these issues were due to npm not being the latest version 3.10.2; using npm 3.9.5 will result in the following issues npm update -g
Error
Error: Cannot find module 'opn'
Error: Cannot find module 'webpack-dev-middleware'
Error: Cannot find module 'express'
Error: Cannot find module 'compression'
Error: Cannot find module 'sockjs'
Error: Cannot find module 'spdy'
Error: Cannot find module 'http-proxy-middleware'
Error: Cannot find module 'serve-index'
If you are using an older version of vue-cli, you may encounter other errors; you need to update vue-cli
npm update vue-cli
Then you can check the current global version of vue-cli
npm view vue-cli
Install this dependency into the project development environment
cnpm install opn --save-dev
cnpm install webpack-dev-middleware --save-dev
cnpm install express --save-dev
cnpm install compression --save-dev
cnpm install sockjs --save-dev
cnpm install spdy --save-dev
cnpm install http-proxy-middleware --save-dev
cnpm install serve-index --save-dev
cnpm install connect-history-api-fallback --save-dev
Start the project again, and an error occurs
ERROR in ./src/main.js
Module build failed: Error: Cannot find module 'babel-runtime/helpers/typeof'
at Function.Module._resolveFilename (module.js:440:15)
at Function.Module._load (module.js:388:25)
at Module.require (module.js:468:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/Volumes/MacStorage/Coding/Web/vue-test/node_modules/.6.17.0@babel-core/lib/transformation/file/index.js:6:16)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
@ multi main
ERROR in ./~/.2.1.0-beta.8@webpack-dev-server/client/socket.js
Module not found: Error: Can't resolve 'sockjs-client' in '/Volumes/MacStorage/Coding/Web/vue-test/node_modules/.2.1.0-beta.8@webpack-dev-server/client'
@ ./~/.2.1.0-beta.8@webpack-dev-server/client/socket.js 1:13-37
@ ./~/.2.1.0-beta.8@webpack-dev-server/client?http://localhost:8080
Install babel-runtime
cnpm install babel-helpers --save-dev
Start the project again, and another error occurs
Module build failed: Error: Cannot find module 'babel-helpers'
Module build failed: Error: Cannot find module 'babel-traverse'
Module build failed: Error: Cannot find module 'json5'
Module build failed: Error: Cannot find module 'babel-generator'
Module build failed: Error: Cannot find module 'detect-indent'
Module build failed: Error: Cannot find module 'jsesc'
If the dependencies are not found, install them again
cnpm install babel-helpers --save-dev
cnpm install babel-traverse --save-dev
cnpm install json5 --save-dev
...not writing anymore, please clear the entire old environment and update to the latest version
Summary of Solutions
Encountering
Module build failed: Error: Cannot find module 'module name'
Then install
cnpm install module name --save-dev (for the environment, it shows that npm run dev cannot be started)
cnpm install module name --save (for the project, such as main.js, it shows that npm run dev is successful but there is an error in the console)
such as escape-string-regexp, strip-ansi, has-ansi, is-finite, emojis-list
Finally, the project can be started
After entering the command, the browser will automatically start. If the default browser is IE, it won't work
npm run dev
The browser will automatically start and you will see this interface.
Start Your Vue Journey
Open the IDE
It is recommended to open the project with Atom and install the Vue syntax highlighting plugin.
Learn the basics using the official documentation
Let's look at an example from the official website (please search for the Chinese documentation online)
Open App.vue in the project directory
Write html in template, js in script, and styles in style. For the sake of convenience, we will write the official example within the same component First. A component can only have one parallel div, which can be written like this, so when copying the official example, just copy the content inside the div.
However, you cannot write it like this:
Second. Data should be written inside the return statement rather than as shown in the documentation.
Incorrect way of writing:
This way, you can finish reading the part of the official documentation before the components on your own.
Playing with Components
Previously, we mostly discussed data binding for various common components. Now, let's talk about using Vue components. Create a component
folder under /src
, and within the component
folder, create a firstcomponent.vue
file. Write a component following the format of App.vue and the knowledge you've learned earlier.
<template>
<div id="firstcomponent">
<h1>I am a title.</h1>
<a> written by {{ author }} </a>
</div>
</template>
<script type="text/javascript">
export default {
data () {
return {
author: "微信公众号 jinkey-love"
}
}
}
</script>
<style>
</style>
Duang... I won't just do as the official documentation says. I need to try it first and then tell you. The effect I achieved is this, hoping the audience achieves the same. (Mysterious smile)
Then, use the component in App.vue (since <div id="app"></div>
is defined in index.html
, we use this component as the main entry for convenience) Step one, import. Write on the first line inside the <script></script>
tag:
import firstcomponent from './component/firstcomponent.vue'
Step two, register. Add components: { firstcomponent }
after the data code block inside the <script></script>
tag. Remember to add an English comma!!!
export default {
data () {
return {
msg: 'Hello Vue!'
}
},
components: { firstcomponent }
}
Step three, use. Add <firstcomponent></firstcomponent>
inside the <template></template>
tag.
<template>
<div id="app">
<img decoding="async" src="./assets/logo.png">
<h1>{{ msg }}</h1>
<firstcomponent></firstcomponent>
</div>
</template>
Completed code:
At this point, take a look at the http://localhost:8080/
page in the browser (it will automatically refresh if you've already opened it). If you don't see the effect, it's because you haven't saved App.vue
and firstcomponent.vue
. After saving, the page will automatically refresh.
Building a Single-Page Application with Routing
We have already installed vue-router via command:
cnpm install vue-router --save
Add an alias in webpack.config.js:
resolve: {
alias: {vue: 'vue/dist/vue.js'}
}
Why add the alias configuration item? Its function can be described in the documentation:
The modified webpack.config.js
looks like this:
var path = require('path')
var webpack = require('webpack')
module.exports = {
entry: './src/main.js',
output: {
path: path.resolve(__dirname, './dist'),
publicPath: '/dist/',
filename: 'build.js'
},
resolveLoader: {
root: path.join(__dirname, 'node_modules'),
},
module: {
loaders: [
{
test: /\\\\\\\\.vue$/,
loader: 'vue'
},
{
test: /\\\\\\\\.js$/,
loader: 'babel',
exclude: /node_modules/
},
{
test: /\\\\\\\\.(png|jpg|gif|svg)$/,
loader: 'file',
query: {
name: '[name].[ext]?[hash]'
}
}
]
},
resolve: {
alias: {vue: 'vue/dist/vue.js'}
},
devServer: {
historyApiFallback: true,
noInfo: true
},
devtool: '#eval-source-map'
}
if (process.env.NODE_ENV === 'production') {
module.exports.devtool = '#source-map'
// http://vue-loader.vuejs.org/en/workflow/production.html
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
})
])
}
Then, write another component, secondcomponent.vue, following the previous method:
<template>
<div id="secondcomponent">
<h1>I am another page</h1>
<a> written by {{ author }} </a>
<p> Thanks to <a href="https://github.com/showonne">showonne</a> for the technical guidance</p>
</div>
</template>
<script>
export default {
data() {
return {
author: "微信公众号 jinkey-love",
articles: [],
}
}
}
}
</script>
<style>
</style>
Now, modify main.js to import and register vue-router
:
import VueRouter from "vue-router";
Vue.use(VueRouter);
And configure the routing rules and add router to the app startup configuration. The old router.map
method is no longer usable in vue-router 2.0
. The modified main.js
is as follows:
import Vue from 'vue'
import App from './App.vue'
import VueRouter from "vue-router";
import VueResource from 'vue-resource'
// Enable debug mode
Vue.config.debug = true;
Vue.use(VueRouter);
Vue.use(VueResource);
// Define components, which can also be imported from other files as taught earlier
const First = { template: '<div><h2>I am the first subpage</h2></div>' }
import secondcomponent from './component/secondcomponent.vue'
// Create a router instance
// And configure the routing rules
const router = new VueRouter({
mode: 'history',
base: __dirname,
routes: [
{
path: '/first',
component: First
},
{
path: '/second',
component: secondcomponent
}
]
})
// Now we can start the application!
// The router will create an App instance and mount it to the element matching the selector #app.
const app = new Vue({
router: router,
render: h => h(App)
}).$mount('#app')
Make these changes and open the browser to see.
Click on the two links to see that the content of <router-view class="view"></router-view>
is displayed, and note that the browser address has changed.
Also, you can write the content of App.vue in main.js, but it's not recommended.
If you are using vue1.0 and vue-router 0.7 version, please refer to the following tutorial, which is quite good, but only for vue1.0:
http://guowenfh.github.io/2016/03/28/vue-webpack-06-router/
Adding Dynamic Data to the Page
At this point, the page is static (the data is fixed and cannot be modified). Most applications will request external data to dynamically change the page content. There is a library called vue-resource
to help us with this.
cnpm install vue-resource --save
Import and register vue-resource
in main.js:
import VueResource from 'vue-resource'
Vue.use(VueResource);
We will dynamically load data on secondcomponent.vue:
<ul>
<li v-for="article in articles">
{{article.title}}
</li>
</ul>
Add the articles array in data and assign it to [] mounted
(refer to the official documentation for the explanation of the vue lifecycle), remember to add a comma between data and mount
mounted: function() {
this.$http.jsonp('https://api.douban.com/v2/movie/top250?count=10', {}, {
headers: {
},
emulateJSON: true
}).then(function(response) {
// This is the correct callback handler
this.articles = response.data.subjects
// this.articles = response.data["subjects"] can also be used
}, function(response) {
// This is the error handling callback
console.log(response)
});
}
Here, the public GET interface of Douban is used. If the interface is a cross-domain POST request, it needs to be configured on the server side:
Access-Control-Allow-Origin: *
Now, let's run it and see. Wait a moment for the interface to return data, hey, the data is loaded, great!
For more usage of vue-router, you can refer to
vue-router 2.0 http://router.vuejs.org/zh-cn/index.html
Saving the Ugly Interface
Components, two-way binding, routing, data requests, and other basic features are now available. By this point, a single-page application is basically taking shape. However, this interface is too ugly. Writing a UI framework from scratch is too laborious? Then find one online.
cnpm install element-ui@next -S
Then import and register in main.js
import Element from 'element-ui'
import 'element-ui/lib/theme-default/index.css'
Vue.use(Element)
Save, and the program throws an error
Uncaught Error: Module parse failed: /Users/**/Desktop/vue2/node_modules/.1.0.0-rc.5@element-ui/lib/theme-default/index.css Unexpected character '@' (1:0)
You may need an appropriate loader to handle this file type.
The official documentation has a pitfall again. The installation tutorial doesn't mention this step, assuming we're all experts... The index.css
file, but webpack can't recognize and convert it to JavaScript during packaging, so configuration is needed to read CSS and font files. Run the command to install the following three things (if previously installed, no need to reinstall)
cnpm install style-loader --save-dev
cnpm install css-loader --save-dev
cnpm install file-loader --save-dev
Add the following configuration to the loaders array in webpack.config.js, remember to add commas where necessary!
{
test: /\.css$/,
loader: "style!css"
},
{
test: /.(eot|woff|woff2|ttf)([?]?.*)$/,
loader: "file"
}
The modified webpack.config.js looks like this
var path = require('path')
var webpack = require('webpack')
module.exports = {
entry: './src/main.js',
output: {
path: path.resolve(__dirname, './dist'),
publicPath: '/dist/',
filename: 'build.js'
},
resolveLoader: {
root: path.join(__dirname, 'node_modules'),
},
module: {
loaders: [
{
test: /\.vue$/,
loader: 'vue'
},
{
test: /\.js$/,
loader: 'babel',
exclude: /node_modules/
},
{
test: /\.css$/,
loader: "style!css"
},
{
test: /.(eot|woff|woff2|ttf)([?]?.*)$/,
loader: "file"
},
{
test: /.(png|jpg|gif|svg)$/,
loader: 'file',
query: {
name: '[name].[ext]?[hash]'
}
}
]
},
resolve: {
alias: {vue: 'vue/dist/vue.js'}
},
devServer: {
historyApiFallback: true,
noInfo: true
},
devtool: '#eval-source-map'
}
if (process.env.NODE_ENV === 'production') {
module.exports.devtool = '#source-map'
// http://vue-loader.vuejs.org/en/workflow/production.html
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
})
])
}
Dress up the Douban movie list with some style:
<el-card class="box-card">
<div slot="header" class="clearfix">
<h2 style="line-height: 36px; color: #20A0FF">Douban Movie Rankings</h2>
</div>
<div v-for="article in articles" class="text item">
{{article.title}}
</div>
</el-card>
Open your browser, enter the URL: http://localhost:8080/second
The list looks much prettier now, and you can refer to the ElementUI documentation to use more component styles
http://element.eleme.io/#/component/layout
npm run build
Another error...orz
ERROR in build.js from UglifyJs
SyntaxError: Unexpected token punc «(», expected punc «:» [build.js:32001,6]
Change the line in node_modules/.bin/cross-env from
require('../dist')(process.argv.slice(2));
Later, it was found that directly running the webpack command can package it
webpack --color --progress
Then upload the index.html and the entire dist directory to the server.
** Share My Notes
-
-
- ```