我是靠谱客的博主 明亮白羊,最近开发中收集的这篇文章主要介绍vue +vuex+vue-router+elementUI+webpack,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

一、环境

  1. node.js环境(npm包管理器)去node官网 https://nodejs.org/en/ 下载
  2. 安装vue-cli 脚手架构建工具(必须在全局中进行安装)
安装命令: 
npm install -g @vue/cli
检查其版本是否正确: 
vue --version

二、构建项目

  1. 输入命令行 vue init webpack my_test
Project name :项目名称 。注意:这里不能使用大写,
Project description:项目描述。
Author:作者,如果你有配置git的作者,他会读取。
vue的打包方式Runtime Only (runtime方式)和 Runtime+Compiler(standalone方式):默认
Install vue-router ? 是否安装vue的路由插件,当然需要。
Use ESLint to lint your code? 是否用ESLint来限制你的代码错误和风格。不要
setup unit tests with Karma + Mocha? 是否需要安装单元测试工具Karma+Mocha,不用
Setup e2e tests with Nightwatch? 是否安装e2e来进行用户行为模拟测试,看自己,不用
should we run ‘npm install’ ……,在选择yes的时候,表示你让程序自动运行命令npm install,你自己就不用手动输入np install来安装依赖了。

npm run dev 运行项目

npm run build打包【环境:development,config/index.js build.assetsPublicPath='./',且在
build/utils.js 中的'vue-style-loader'中添加 [publicPath: '../../']

三、下载依赖

npm install --save-dev less-loader less

npm install sass-loader node-sass webpack --save-dev
npm install style-loader css-loader --save-dev

npm i element-ui -S

npm install axios

npm install vuex --save

markdown 编辑器
npm install mavon-editor --save

vuex持久化
vuex-persistedstate

npm install echarts -S

存储
npm install js-cookie --save
  1. less使用
    style lang=“less” scoped
    less 版本过高【npm uninstall less-loader 】【npm install less-loader@5.0.0】
    sass使用
    在package.json中粘贴,下载
	"node-sass": "^4.7.2",
	"sass-loader": "6.0.6",
  1. element-ui使用【main.js】
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';

Vue.use(ElementUI);
  1. axios 【新建utils/request.js】
import axios from 'axios'
import { Message, Loading } from 'element-ui'
import store from '@/store'
import router from '@/router'
import { setToken, getToken } from '@/utils/auth'

let globalLoading

function startLoading() {
    globalLoading = Loading.service({
        lock: true,
        text: '加载中…',
        background: 'rgba(0, 0, 0, 0.7)'
    })
}
function endLoading() {
    setTimeout(() => {
        globalLoading.close()
    }, 2000)
}

let needLoadingRequestCount = 0
export function showFullScreenLoading() {
    if (needLoadingRequestCount === 0) {
        startLoading()
    }
    needLoadingRequestCount++
}

export function tryHideFullScreenLoading() {
    if (needLoadingRequestCount <= 0) return
    needLoadingRequestCount--
    if (needLoadingRequestCount === 0) {
        endLoading()
    }
}
// create an axios instance
const request = axios.create({
    timeout: 1500000 // request timeout
})

// request interceptor
request.interceptors.request.use(config => {
    // Do something before request is sent
    if (store.getters.token) {
        config.headers['X-Token'] = getToken() // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
    }
    showFullScreenLoading()
    return config
}, error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
})

// respone interceptor
request.interceptors.response.use(
    response => {
        tryHideFullScreenLoading()
        const res = response.data;
        if (res.code == 520) {
            store.dispatch('FedLogOut').then(() => {

            });
        } else {
            return response;
        }
    },
    error => {
        console.log('err' + error)// for debug
        Message({
            message: error.message,
            type: 'error',
            duration: 8 * 1000
        })
        return Promise.reject(error)
    })

export default request


【main.js】

const axios = require("axios")
import axios from './utils/request';
Vue.prototype.$axios = axios
  1. vuex 使用【新建store/index.js】
import Vue from 'vue'
import Vuex from 'vuex'
import user from './modules/user'
import getters from './getters'

Vue.use(Vuex)

const store = new Vuex.Store({
    modules: {
        user
    },
    getters
})

export default store

【新建store/getters.js】

const getters = {
    token: state => state.user.token,
    userInfo: state => state.user.userInfo,
}
export default getters

【新建store/modules/user.js】

import { Message } from 'element-ui'
import { loginByUsername, logout, getUserInfo } from '@/api/login'
import { setToken, getToken, setOrgToken, getOrgToken, setUserName, getUserName, removeToken, setUserMenu, getUserMenu } from '@/utils/auth'
import { request } from '@/api/common'

const user = {
    state: {
        userInfo: '',
        token: getToken(),
    },

    mutations: {
        SET_USETINFO: (state, userInfo) => {
            state.userInfo = userInfo
        },
        SET_TOKEN: (state, token) => {
            state.token = token
        },
    },
    actions: {
        // 用户名登录
        LoginByUsername({ commit }, userInfo) {
            const username = userInfo.username.trim()
            return new Promise((resolve, reject) => {
                loginByUsername(username, userInfo.password).then(response => {
                    console.log('response', response)
                    if (response.data.success) {
                        setToken(response.data.data.token)
                        setUserName(response.data.data.userInfo.nickName)
                        commit('SET_TOKEN', response.data.data.token)
                        commit('SET_USETINFO', response.data.data.userInfo)
                    } else {
                        reject()
                        Message({
                            message: response.data.message,
                            type: 'error'
                        })
                    }
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // 获取用户信息
        GetUserInfo({ commit, state }) {
            return new Promise((resolve, reject) => {
                request({}, 'auth/refreshLoginInfo').then(res => {
                    if (res.data.success) {
                        const result = res.data.data.userInfo
                        let menuList = []
                        let token = getToken()
                        let schoolList = localStorage.getItem(schoolName)
                        commit('SET_TOKEN', token)
                        commit('SET_USER_TYPE', result.userType)
                        resolve(menuList)
                    } else {
                        resolve()
                    }
                }).catch(() => {
                    reject()
                })
            })
        },

        // 登出
        LogOut({ commit, state }) {
            return new Promise((resolve, reject) => {
                logout(state.token).then(() => {
                    commit('SET_TOKEN', '')
                    commit('SET_ROLES', [])
                    removeToken()
                    resolve()
                }).catch(error => {
                    reject(error)
                })
            })
        },

        // 前端 登出
        FedLogOut({ commit }) {
            return new Promise(resolve => {
                commit('SET_TOKEN', '')
                removeToken()
                resolve()
            })
        },
    }
}
export default user
  1. vue-router 使用
import Vue from 'vue'
import Router from 'vue-router'
import { getToken } from '@/utils/auth'

Vue.use(Router)

const router = new Router({
    routes: [
        {
            path: '/',
            name: 'HelloWorld',
            component: () => import('@/components/HelloWorld')
        }
    ]
})

//获取原型对象上的push函数
const originalPush = Router.prototype.push
//修改原型对象中的push方法
Router.prototype.push = function push(location) {
    return originalPush.call(this, location).catch(err => err)
}
router.beforeEach((to, from, next) => {
    if (getToken()) { // determine if there has token
        if (to.path === '/login') {
            next({ path: '/' })
        } else {
            store.dispatch('GetUserInfo').then(res => { // 拉取user_info
                next()
            }).catch((err) => {
                store.dispatch('FedLogOut').then(() => {
                    Message.error(err || 'Verification failed, please login again')
                    next({ path: '/login' })
                })
            })
        }
    } else {
        next('/login') // 否则全部重定向到登录页
    }
})

export default router

  1. js-cookie 使用 新建【utils/auth.js】
import Cookies from 'js-cookie'

const sessionKey = 'MATHSESSION'
const UserToken = 'MATHTOKEN'
const UserOrgToken = 'User-Org-Token'
const UserMenu = 'User-Menu'  // 用户菜单
const UserName = 'User-Name'   // 用户名
const PAGES = 'User-Permission-Pages'   // 页面权限

// session
export function setXToken(token) {
    return Cookies.set(sessionKey, token, {
        expires: 1 / 48
    });
}

export function getXToken() {
    return Cookies.get(sessionKey)
}

// set/get token
export function setToken(token) {
    // localStorage.setItem(UserToken, token)
    return Cookies.set(UserToken, token)
}

export function getToken() {
    // if(Cookies.get(UserToken)){
    return Cookies.get(UserToken)
    // }else{
    //   return localStorage.getItem(UserToken)
    // }
}

// set/get orgtoken
export function setOrgToken(token) {
    return Cookies.set(UserOrgToken, token)
}

export function getOrgToken() {
    return Cookies.get(UserOrgToken)
}

// set/get menu
export function setUserMenu(token) {
    return Cookies.set(UserMenu, token)
}

export function getUserMenu() {
    return Cookies.get(UserMenu)
}

//set/get PAGES
export function setPages(token) {
    return Cookies.set(PAGES, token)
}

export function getPages() {
    return Cookies.get(PAGES)
}

// set/get username
export function setUserName(token) {
    return Cookies.set(UserName, token)
}

export function getUserName() {
    return Cookies.get(UserName)
}

// remove cookies
export function removeToken() {
    Cookies.remove(UserOrgToken)
    Cookies.remove(UserMenu)
    Cookies.remove(UserName)
    return Cookies.remove(UserToken)
}

【mian.js】

import store from './store/index'
new Vue({
  el: '#app',
  router,
  // store,
  components: { App },
  template: '<App/>'
})
  1. mavonEditor【main.js】
import Vue from 'vue'
import mavonEditor from 'mavon-editor'
import 'mavon-editor/dist/css/index.css'
Vue.use(mavonEditor)

【组件中引入】参考
6. echars 参考

最后

以上就是明亮白羊为你收集整理的vue +vuex+vue-router+elementUI+webpack的全部内容,希望文章能够帮你解决vue +vuex+vue-router+elementUI+webpack所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(54)

评论列表共有 0 条评论

立即
投稿
返回
顶部