preface

On the way home during the National Day, I learned that the official version of VUe2 was released. After the National Day, VUe2 was directly applied in two projects of the company, one is the merchant background of PC terminal and the other is the mall of wechat terminal, which are based on vue2, VUE-Router and vuex...... In the process of development, I encountered a series of problems, such as page backward data restoration, scrollbar restoration, login timeout, obtaining list data, form submission, and automatic deployment of multiple servers. Finally, they were solved one by one. I was able to smoothly switch from React to VUe2 development, thanks to the documentation of VUE.Copy the code

Github:github.com/lzxb/vue2-d…

The source code that

Project Directory Description

.
|-- config                           // Project development environment configuration
|   |-- index.js                     // Package the project deployment configuration
|-- src                              // Source directory
|   |-- components                   // Public components
|       |-- header.vue               // Page header public component
|       |-- index.js                 // Load various common components
|   |-- config                       // Route configuration and program basic information configuration
|       |-- routes.js                // Configure page routing
|   |-- css                          // Various CSS files
|       |-- common.css               // Global generic CSS file
|   |-- iconfont                     // Various font ICONS
|   |-- images                       // Public image
|   |-- less                         // Various less files
|       |-- common.less              // Global generic less files
|   |-- pages                        // Page component
|       |-- home                     // Personal center
|       |-- index                    // The first page of the website
|       |-- login                    / / login
|       |-- signout                  / / exit
|   |-- store                        // VuEX state management
|       |-- index.js                 // Load various store modules
|       |-- user.js                  / / the user store
|   |-- template                     // Various HTML files
|       |-- index.html               // Program entry HTML file
|   |-- util                         // Public js method, vue mixin blending
|   |-- app.vue                      // page entry file
|   |-- main.js                      // Program entry file to load various common components
|-- .babelrc                         // ES6 syntax compiler configuration
|-- gulpfile.js                      // Start, package, deploy, automate build
|-- webpack.config.js                // Package the configuration
|-- server.js                        // Proxy server configuration
|-- README.md                        // Project description
|-- package.json                     // Configure the project information. You can create the project by running the NPM init command
.Copy the code

1. HTML entry file. The source file path is SRC /template/index.html


      
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0, the minimum - scale = 1.0, the maximum - scale = 1.0, user - scalable = no, minimal - UI">
    <title>vue2-demo</title>
</head>

<body>
    <div id="app">
        <router-view></router-view>
    </div>
</body>

</html>Copy the code

2. The source file path is SRC /main.js

import Vue from 'vue'
import VueRouter from 'vue-router'

import routes from './config/routes'
import store from './store/'
import components from './components/' // Load the public component

import './css/common.css'
import './less/common.less'

Object.keys(components).forEach((key) = > {
    var name = key.replace(/(\w)/, (v) => v.toUpperCase()) // Uppercase
    Vue.component(`v${name}`, components[key])
})

Vue.use(VueRouter)

const router = new VueRouter({
    routes
})
router.beforeEach(({meta, path}, from, next) = > {
    var { auth = true } = meta
    var isLogin = Boolean(store.state.user.id) // True the user has logged in. False The user has not logged in

    if(auth && ! isLogin && path ! = ='/login') {
        return next({ path: '/login' })
    }
    next()
})

new Vue({ store, router }).$mount('#app')Copy the code

3. Configure the page route, permission configuration, and source file path: SRC /config/routes.js

import App from '.. /app'

export default[{path: '/'.component: App,
        children: [{path: '/login'./ / login
                meta: { auth: false },
                component: resolve= > require(['.. /pages/login/'], resolve)
            },
            {
                path: '/signout'./ / exit
                component: resolve= > require(['.. /pages/signout/'], resolve)
            },
            {
                path: '/home'.// Personal homepage
                component: resolve= > require(['.. /pages/home/'], resolve)
            },
            {
                path: '/'./ / home page
                meta: { auth: false },
                component: resolve= > require(['.. /pages/index/'], resolve)
            },
            {
                path: The '*'.// The login page is forcibly redirected to other pages
                redirect: '/login'}}]]Copy the code

4. Page entry component, source file path: SRC /app.vue

<style lang="less" scoped>

</style>
<template>
    <router-view></router-view>
</template>
<script>
    export default{}</script>Copy the code

5. Store instantiation, import various modules, source file path: SRC /store/index.js

import Vue from 'vue'
import Vuex from 'vuex'
import user from './user'

Vue.use(Vuex)

export default new Vuex.Store({
    strict: process.env.NODE_ENV ! = ='production'.// In non-production environments, use strict mode
    modules: {
        user
    }
})Copy the code

6. Define the store User module. The source file path is SRC /store/user.js

import Vue from 'vue'

export const USER_SIGNIN = 'USER_SIGNIN' // Login succeeded
export const USER_SIGNOUT = 'USER_SIGNOUT' // Log out

export default {
    state: JSON.parse(sessionStorage.getItem('user')) || {},
    mutations: {
        [USER_SIGNIN](state, user) {
            sessionStorage.setItem('user'.JSON.stringify(user))
            Object.assign(state, user)
        },
        [USER_SIGNOUT](state) {
            sessionStorage.removeItem('user')
            Object.keys(state).forEach(k= > Vue.delete(state, k))
        }
    },
    actions: {
        [USER_SIGNIN]({commit}, user) {
            commit(USER_SIGNIN, user)
        },
        [USER_SIGNOUT]({commit}) {
            commit(USER_SIGNOUT)
        }
    }
}Copy the code

7. Load various public components. The source file path is SRC /components/index.js

import header from './header'
export default { header }Copy the code

8. Encapsulate the common header component of the page with the source file path: SRC /components/header.js

<style lang="less" scoped>.header { position: relative; line-height: 38px; color: #fff; text-align: center; background: #222; .item { position: absolute; top: 0; bottom: 0; z-index: 1; a { color: #fff; } } .left { left: 10px; } .right { right: 10px; }}</style>
<template>
    <header class="header">
        <div class="item left">
            <slot name="left"></slot>
        </div>
        <div class="title">{{title}}</div>
        <div class="item right">
            <slot name="right"></slot>
        </div>
    </header>
</template>
<script>
    export default {
        props: {
            title: {
                type: String.default: ' '}}}</script>Copy the code

9. Import the global public CSS. The source file path is SRC/CSS /common.css

input::-webkit-outer-spin-button.input::-webkit-inner-spin-button{  
    -webkit-appearance: none ! important;  
    margin: 0;  
}Copy the code

10. Import global public less. The source file path is SRC /less/common.less

* {
    padding: 0;
    margin: 0;
}Copy the code

11. Create the home page. The source file path is SRC /pages/index.vue

<style lang="less" scoped>
    .login-msg {
        padding: 50px;
        text-align: center;
    }
    .msg {
        padding: 50px;
        text-align: center;
        font-size: 20px;
        color: red;
    }
</style>
<template>
    <div>
        <v-header title="Home page">
            <router-link slot="right" v-if="user.id" to="/home">{{user.name}}</router-link>
        </v-header>
        <div class="login-msg" v-if=! "" user.id">
            <router-link to="/login">You have not logged in yet, please log in first</router-link>
        </div>
        <div class="msg" v-if="user.id">
            <img width="50" :src="logo" alt=""> <br>Haha, congratulations on getting into the pit of Vue2</div>
    </div>
</template>
<script>
    import { mapState } from 'vuex'
    import logo from './logo.png'
    export default {
        data() {
            return {
                logo
            }
        },
        computed: mapState({ user: state= > state.user }),
    }
</script>Copy the code

12. Create a login page. The source file path is SRC /pages/login.vue

<style lang="less" scoped>.login { padding: 50px; text-align: center; .line { padding: 5px; input { padding: 0 10px; line-height: 28px; } } button { padding: 0 20px; margin-top: 20px; line-height: 28px; }}</style>
<template>
    <div>
        <v-header title="Login">
            <router-link slot="left" to="/">return</router-link>
        </v-header>
        <form class="login" v-on:submit.prevent="submit">
            <div class="line">    
                <div v-show="btn && ! form.id">Id cannot be empty</div>
                <input type="number" placeholder="Enter your ID" v-model="form.id">
            </div>
            <div class="line">
                <div v-show="btn && ! form.name">The user name cannot be empty</div>
                <input type="text" placeholder="Enter your username" v-model="form.name">
            </div>
            <button>The login</button>
        </form>
    </div>
</template>
<script>
    import { mapActions } from 'vuex'
    import { USER_SIGNIN } from 'store/user'

    export default {
        data() {
            return {
                btn: false.// True is committed, false is not committed
                form: {
                    id: ' '.name: ' '}}},methods: {
            ...mapActions([USER_SIGNIN]),
            submit() {
                this.btn = true
                if(!this.form.id || !this.form.name) return
                this.USER_SIGNIN(this.form)
                this.$router.replace({ path: '/home'})}}}</script>Copy the code

13. Create a personal home page. The source file path is SRC /pages/home.vue

<style lang="less" scoped>

</style>
<template>
    <div>
        <v-header title="Home page">
            <router-link slot="left" to="/">Home page</router-link>
            <router-link slot="right" to="/signout">exit</router-link>
        </v-header>
        <div style="padding: 50px;">{{user.name}} Welcome home</div>
    </div>
</template>
<script>
    import { mapState } from 'vuex'
    export default {
        computed: mapState({ user: state= > state.user }),
    }
</script>Copy the code

14. Create exit page, source file path: SRC /pages/signout.vue

<style lang="less" scoped>.btn { padding: 50px; text-align: center; button { padding: 5px 10px; }}</style>
<template>
    <div>
        <v-header title="Quit">
            <router-link slot="left" to="/home">return</router-link>
        </v-header>
        <div class="btn">
            <button v-on:click="submit">Confirm the exit</button>
        </div>
    </div>
</template>
<script>
    import { mapActions } from 'vuex'
    import { USER_SIGNOUT } from 'store/user'
    export default {
        methods: {
            ...mapActions([USER_SIGNOUT]),
            submit() {
                this.USER_SIGNOUT()
                this.$router.replace({ path: '/login'})}}}</script>Copy the code

To advance vue2

Vue2 reconstructs the CNode community, which will be completed soon, with an update from0Build vue2 complete project, you can use the simplest way to achieve page back state restoration, local scrollbar restoration, etc.Copy the code