Vue-Element(一)项目的创建

说明

自用
资料: vue实现动态注册并渲染组件

版本

vue: 2.9.6
webpack: 3.12.0

一、安装 webpack

全局安装

npm install webpack -g

查看安装

webpack -v

二、安装vue-cli

npm install vue-cli -g

三、创建项目

vue init webpack projectname(项目的名称)

四、安装依赖

进入项目文件夹后执行npm install

cd workbench
npm install

五、安装和设置element-ui

官网:https://element.eleme.cn

安装
npm i element-ui -S
完整引入

在 main.js 中写入以下内容:

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'

Vue.use(ElementUI)

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: ''
})

六、安装http库和配置http请求设置

安装axios
npm install axios
配置request请求

src下新建utils/request.jsrequest.js内容如下:

import axios from 'axios'
import qs from 'qs'
import {Message} from 'element-ui'

// create an axios instance
const service = axios.create({
  baseURL: 'http://10.10.20.35:8000/api', // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000, // request timeout
  showLoading: true,
})

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    console.log('request=>', config)
    if (config.headers['Content-Type'] === 'application/x-www-form-urlencoded') {
      config.data = qs.stringify(config.data)
    }
    return config
  },
  error => {
    // do something with request error
    console.log('request.error=>', error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    console.log('response=>', response)

    const res = response.data

    if (res.code < 0) {

      Message({
        message: res.msg || 'Error',
        type: 'error',
        duration: 2 * 1000
      })

      return Promise.reject(res.msg || 'Error')
    } else {
      return res
    }
  },
  error => {
    console.log('response.error=>', error) // for debug
    Message({
      message: error.message || 'Error',
      type: 'error',
      duration: 2 * 1000
    })
    return Promise.reject(error)
  }
)

export default service

新建 api 和 views
测试接口访问正常

user.js中新增登录接口

import request from '@/utils/request.js'

export const login = (data) => {
  return request({
    url: 'user/login',
    method: 'post',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    data
  })
}

新增登录视图login.vue







src 下的 app.vue修改为






src/router/index.js修改为

import Vue from 'vue'
import Router from 'vue-router'
import Login from '@/views/user/login'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Login',
      component: Login
    }
  ]
})

执行命令

npm run dev

成功后访问http://localhost:8080

初次访问

输入登录信息,点击登录后报错:
Access to XMLHttpRequest at 'http://10.10.20.35:8000/api/user/login' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
出现跨域问题。

登录报错

七、解决跨域问题

在项目目录下config/index.js中新增如下配置:

module.exports = {
  dev: {

    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      "/api": {
        target: 'http://10.10.20.35:8000/api',
        pathRewrite:{
          '^/api':''
        }
      }
    },
    ..... 此处省略原有配置
}

config/dev.env.js中新增:

module.exports = merge(prodEnv, {
  NODE_ENV: '"development"',
  baseUrl: '"/api"'
})

config/prod.env.js中新增

'use strict'
module.exports = {
  NODE_ENV: '"production"',
  baseUrl: '"http://10.10.20.35:8000/api/"' //此次填写生产环境域名
}

src/utils/request.jsbaseURL修改如下

// create an axios instance
const service = axios.create({
  baseURL: process.env.baseUrl, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000, // request timeout
  showLoading: true
})

再次运行后,尝试登录:


登录成功

八、vue 多环境配置

参考如下:

https://www.cnblogs.com/itmrzhang/p/11008280.html

九、将index.html转移到src

index.html位置

原位置

index.html转移到src
转移后

转移后需要修改build/webpack.dev.conf.js

    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: './src/index.html',
      inject: true
    }),

转移后还需要修改build/webpack.prod.conf.js

    new HtmlWebpackPlugin({
      filename: config.build.index,
      template: './src/index.html',
      inject: true,
      minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeAttributeQuotes: true
        // more options:
        // https://github.com/kangax/html-minifier#options-quick-reference
      },
      // necessary to consistently work with multiple chunks via CommonsChunkPlugin
      chunksSortMode: 'dependency'
    }),

你可能感兴趣的:(Vue-Element(一)项目的创建)