说明
自用
资料: 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
安装
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: '<App/>'
})
六、安装http库和配置http请求设置
安装axios
npm install axios
配置request请求
在src
下新建utils/request.js
,request.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
<template>
<el-form :model="userForm" label-width="80px" class="user-login">
<el-form-item label="用户名">
<el-input v-model="userForm.user"></el-input>
</el-form-item>
<el-form-item label="密码">
<el-input v-model="userForm.password" type="password"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm">登陆</el-button>
</el-form-item>
</el-form>
</template>
<script>
import {login} from '@/api/user'
import {Message} from 'element-ui'
export default {
name: 'login',
data () {
return {
userForm: {
user: '',
password: ''
}
}
},
methods: {
submitForm () {
login(this.userForm).then(result => {
Message(result.msg)
})
}
}
}
</script>
<style scoped>
.user-login {
width: 500px;
}
</style>
将 src
下的 app.vue
修改为
<template>
<router-view/>
</template>
<script>
export default {
name: 'App'
}
</script>
<style>
</style>
将 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.js
将baseURL
修改如下
// 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 多环境配置
参考如下:
九、将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'
}),