3. Install Webpack-HTML-Plugin
4 Install Vue
5 Install Webpack-DEV-Server hot update
6 Install Babel
7 Install Vue-loader to process Vue files
8 Use the route Vue-Router2
9.1vuex basic application
9.2State's split
10 componentization, and between components
11. Use nodejs+koa2 to provide background interfaces
12. Set KOA to allow front -end cross -domain access
13 Use AXIOS to access the background interface
git clone https://github.com/liubin915249126/vue2-study.git
cd vue2-study
安装cnpm镜像
npm install -g cnpm --registry=https://registry.npm.taobao.org
npm install //安装依赖包
npm start //启动项目
CD 'to/your/path' npm init
Divided into global installation and project installation
npm install webpack -g
npm install webpack --save-dev
const path = require('path');
module.exports = {
entry: './Script/main.js', //项目入口文件
output:{ //输出编译后文件地址及文件名
path: path.resolve(__dirname, 'dist'),
filename: 'js/bundle.js'
}
};
You can see the compiled file after executing the webpack command in the command line
NPM Install HTML-WEBPACK-PLUGIN-Save-DEV
const HtmlWebpackPlugin = require('html-webpack-plugin');
...
plugins:[
...
new HtmlWebpackPlugin({
title:'react 学习',
inject:'body',
filename:'index.html',
template:path.resolve(__dirname, "index.html")
}),
...
]
After executing the webpack command again, you can see that an index.html file. This file. This file is the effect based on the template and automatically introduced the packed js file.
npm install vue -save
Modify main.js:
import Vue from 'vue';
var MainCtrl = new Vue({
el:'#main',
data:{
message:'Hello world'
}
})
Modify index.html:
<div id="main">
<h3>{{message}}</h3>
</div>
Execute webpack packaging and running index.html (packaged files) to report an error. After investigation, configuration in webpack.config.js:
...
resolve: { alias: { 'vue': 'vue/dist/vue.js' } }
You can see the effect after running again
npm install webpack-dev-server -g
npm install webpack-dev-server --save-dev
npm install vue-hot-reload-api --save-dev
Configure webpack.config.js
...
devServer: {
historyApiFallback: true,
},
...
Configure the command in Package.json
"start":"webpack-dev-server --hot --inline --progress --open"
Execute the NPM Start browser to automatically open the page. After changing the file, you can see the real -time update of the page
Before using the .vue file
npm install babel-core babel-loader babel-plugin-transform-runtime --save-dev
npm install babel-preset-stage-0 babel-runtime babel-preset-es2015 --save-dev
Project root directory new .babelrc file and configuration:
{
"presets": ["es2015", "stage-0"],
"plugins": ["transform-runtime"]
}
Install loader processing .css, .vue file
npm install css-loader style-loader vue-loader vue-html-loader --save-dev
Configure webpack.config.js
...
module:{
loaders: [
{test: /.js$/,loader: 'babel-loader',exclude: /node_modules/},
{test: /.vue$/,loader: 'vue-loader'}]
},
//vue: {loaders: {js: 'babel'}}
...
Error after configuration: Cannot Find Module 'Vue-Template-Compiler' Install Vue-Template-Compiler
cnpm install vue-template-compiler --save-dev
Modify index.html:
<body>
<div id="main">
<app></app>
</div>
</body>
New SRC/Index.vue:
<template>
<div class="message">{{ msg }}</div>
</template>
<script>
export default {
data () {
return {
msg: 'Hello from vue-loader!'
}
}
}
</script>
<style>
.message {
color: blue;
}
</style>
Modify main.js
...
import App from './src/index.vue';
new Vue({
el: '#main',
components: { App }
})
After saving, run NPM Start to see the effect
Modify the code and see the modified effect.
First install Vue-Router:
npm install vue-router --save
Modify main.js:
1. Introduce the APP, About two components to introduce router components to introduce subclasses Child
import App from './src/index.vue';
import About from './src/about.vue';
import Child from './src/children.vue'
import VueRouter from 'vue-router';
Vue.use(VueRouter)
2. Define the routing: The embedded routing is stored in children: [], the subcutor is in the parent component
<router-view></router-view>
Rendering, routing through "/: ID" defines parameters through link "/About/123" passing parameters in the component to obtain the passportation parameter through {{$ route.params.id}}
const routes = [
{ path: '/index', component: App },
{ path: '/about/:id', component: About ,children:[
{ path: 'child', component: child}
]}
]
routes
configuration const router = new VueRouter({
routes // (缩写)相当于 routes: routes
})
const app = new Vue({
router
}).$mount('#main')
5. Modify the index.html file
<div id="main">
<p>
<router-link to="/index">index</router-link>
<router-link to="/about/123">about</router-link>
<router-link to="/about/123/child">child router</router-link>
</p>
<!-- 路由匹配到的组件将渲染在这里 -->
<router-view></router-view>
</div>
6. Modify the parent component About.vue writing before discovering that there can only be a top HTML tag
</template>
<div>
<div class="message">{{ msg }}</div>
<div>
<span>传递的参数为:{{ $route.params.id }}</span>
<router-view></router-view>
</div>
</div>
</template>
routes: [
...
{ path: '/a', redirect: '/index' }
]
When visiting/A, the component corresponding to the jump value/index
When writing a single page application with Vue.js, the packaged JavaScript package will be very large, affecting the loading of the page. We can use the routing lazy load to optimize this problem. Change the route writing to:
//定义路由
const routes = [
{ path: '/index', component: resolve => require(['./src/index.vue'], resolve) },
{
path: '/about/:id', component: resolve => require(['./src/about.vue'], resolve) ,
children:[
{ path: 'child', component: resolve => require(['./src/children.vue'], resolve)}
]},
{ path: '/a', redirect: '/index' }
]
// 字符串
router.push('home')
// 对象
router.push({ path: 'home' })
// 命名的路由
router.push({ name: 'user', params: { userId: 123 }})
// 带查询参数,变成 /register?plan=private
router.push({ path: 'register', query: { plan: 'private' }})
References: Vue-Router Effect Figure:
Install Vuex
npm install vuex --save
New Store.js file:
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex)
//创建Store实例
const store = new Vuex.Store({
// 存储状态值
state: {
count:1
},
// 状态值的改变方法,操作状态值
// 提交mutations是更改Vuex状态的唯一方法
mutations: {
increment(state){
state.count++;
},
decrement(state){
state.count--;
}
},
// 在store中定义getters(可以认为是store的计算属性)。Getters接收state作为其第一个函数
getters: {
},
actions: {
}
})
// 要改变状态值只能通过提交mutations来完成
export default store;
Inject Store into main.js;
...
//引入store
import store from './store.js'
...
const app = new Vue({
router,
store
}).$mount('#main')
Create a new Count.Vue file, and build a new route to point to the use component with reference to Vue-Router. count.vue file:
<template>
<div>
<div>{{$store.state.count}}</div>
<div>
<span @click="increment">increment</span>
<span @click="decrement">decrement</span>
</div>
</div>
</template>
<style>
</style>
<script>
export default {
data(){
return {};
},
methods:{
increment(){
this.$store.commit('increment')
},
decrement(){
this.$store.commit('decrement')
}
}
}
</script>
Effect map:
Due to the use of a single state tree, all the state applied to a relatively large object will be concentrated. When the application becomes very complicated, the Store object may become quite bloated. To solve the above problems, Vuex allows us to divide the store into modules. Each module has its own State, Mutation, Action, Getter
New modulea.js, moduleb.js
And modify store.js:
...
import moduleA from './moduleA';
import moduleB from './moduleB';
...
Vue.use(Vuex)
//创建Store实例
const store = new Vuex.Store({
modules:{
moduleA, moduleB //es6的写法,合并模块
}
})
...
In the component, you need to use it to visit the state.
$store.state.moduleA.count
$store.state.moduleB.Name
Effect map: Mutations is still unchanged to modify the state
Component is one of the most powerful features of Vue.js. The component can extend the HTML element and encapsulate the reusable code. At a high level, components are custom elements, and Vue.js compilers add special features to it. In some cases, components can also be manifested as native HTML elements expanded with IS characteristics.
Component A writing:
<template>
<div class="componentA">
...
</div>
</template>
<script>
export default {
data () {
return {
msg: 'component-A',
}
}
}
</script>
<style>
</style>
Component B writing:
<template>
<div class="message" id="componentB">
...
</div>
</template>
<script>
import Vue from 'vue'
export default Vue.component('my-component', {
template: '#componentB ',
data(){
return {
msg: 'component-B',
}
}
})
</script>
<style>
</style>
Quote from the parent component component to be hung in
<template>
<div>
<component-A ></component-A>
<component-B></component-B>
</div>
</template>
<script>
import componentA from './component-a.vue';
import componentB from './component-b.vue'
export default {
data () {
return {
}
},
components:{
"component-A":componentA,
"component-B":componentB
}
}
</script>
<style>
</style>
For the communication between the simple parent and son component or the brothers component of the same parent component, Vue provides a method, there is no need to use Vuex
Father component:
<component-A :logo="logoMsg"></component-A> //logoMsg是父组件data里的值
Sub -component:
<template>
<div class="componentA">
<div>{{logo}}</div>
</div>
</template>
...
data(){
}
props:["logo"],
...
Father component:
<component-A :logo="logoMsg" @toParent="componenta"></component-A>
...
methods:{
componenta:function(data){ //data就是子组件传递过来的值
this.data1 = data
}
}
Sub -component:
methods:{
toParent:function(){
this.$emit('toParent',this.data1) //调用父组件toParent方法,并传递参数
}
}
Effect map:
Effect map:
bus.js file:
import Vue from 'vue'
export default new Vue()
Component B $ emit trigger event:
import Bus from './bus.js'
...
byBus:function(){
Bus.$emit('byBus',this.byBusData)
}
Component A $ on accepting event transmission data
...
data(){
},
created(){
Bus.$on('byBus',(data)=>{
this.busData = data
})
},
Effect map:
NPM Install Koa Koa-Router-Save-DEV
Create a new server/index.js file index.js under the root directory:
const Koa = require('koa');
const router = require('koa-router')();
const app = new Koa();
router.get('/', (ctx, next)=> {
ctx.response.body = '111'
});
app
.use(router.routes())
.use(router.allowedMethods());
app.listen(3000,()=>{
console.log('server is start at port 3000')
});
Set commands in Package.json: "Server": "Node Server Index.js" Starting Service: NPM Run Server Visit LocalHost/3000
Use KOA2-Cors to set cross-domain installation NPM Install KOA2-Cors-Save-DEV
...
app.use(cors({
origin: function (ctx) {
if (ctx.url === '/test') {
return false;
}
return '*';
},
exposeHeaders: ['WWW-Authenticate', 'Server-Authorization'],
maxAge: 5,
credentials: true,
allowMethods: ['GET', 'POST', 'DELETE'],
allowHeaders: ['Content-Type', 'Authorization', 'Accept'],
}));
...
Install AXIOS:
npm install axios --save
Create a new server/request.js in the root directory and encapsulate a Request function. All requests pass through the Request function, which is convenient for the request for uniform processing
import axios from 'axios'
let BASE_URL = 'http1://localhost:3000'
export default function request(data){
let options = {...data}
options.url = `${BASE_URL}${data.url}`
return axios(options)
.then(checkStatus)
.then(parseJSON)
.catch()
}
(Pit) Axios.Defaults.Withcredentials = "Include" // When request, bring cookie axios request to set the need to set it without cookies. "To explain the protocol+domain name+port request data renderings: renderings
Installation: NPM I Element -UI -S Introduction:
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-default/index.css'
Vue.use(ElementUI)
Use: Configure CSS before using, File loader install style-loader, CSS-loader
npm install css-loader style-loader file-loader --save-dev
{
test: /.css$/,
loader: 'style-loader!css-loader'
},
{
test: /.(eot|svg|ttf|woff|woff2)(?S*)?$/,
loader: 'file-loader'
},
{
test: /.(png|jpe?g|gif|svg)(?S*)?$/,
loader: 'file-loader',
query: {
name: '[name].[ext]?[hash]'
}
}
Install:
cnpm install less less-loader --save-dev
use:
<style lang='less'>
.articleWrap{
.articleTop{
color:red;
}
}
</style>
1. Routing jump to pass on the parameters:
<router-link :to="{ name:'articleinfo',params:{id:index}}"></router-link>
2. Use rich text editor: Vue2-Editor Install: CNPM Install Vue2-Editor-Save use: Import {vueeditor} from 'vue2-Editor'
Use Cross-EnV: Set the development environment Installation: CNPM Install Cross-Eenv-Save-DEV configuration command:
"start": "cross-env NODE_ENV=development webpack-dev-server --hot --inline --progress --open",
"build":"cross-env NODE_ENV=production webpack"
Modify webpack configuration:
if (process.env.NODE_ENV === 'production') {
config.plugins = (config.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production'),
},
IS_PRODUCTION: true
}),
/*new webpack.optimize.UglifyJsPlugin({
compress: {warnings: false},
sourceMap: false
}),*/
]);
}
else {
config.plugins = (config.plugins || []).concat([
new webpack.DefinePlugin({
'process.env':
{
'NODE_ENV': JSON.stringify('development'),
},
IS_PRODUCTION: false
}),
]);
}
Pass in the program: process.env.node_env to get the current environment variable