說明
自用
資料: vue實現(xiàn)動態(tài)注冊并渲染組件
版本
vue: 2.9.6
webpack: 3.12.0
一锈候、安裝 webpack
全局安裝
npm install webpack -g
查看安裝
webpack -v
二讼积、安裝vue-cli
npm install vue-cli -g
三往毡、創(chuàng)建項目
vue init webpack projectname(項目的名稱)
四赌渣、安裝依賴
進入項目文件夾后執(zhí)行npm install
cd workbench
npm install
五晓淀、安裝和設(shè)置element-ui
安裝
npm i element-ui -S
完整引入
在 main.js 中寫入以下內(nèi)容:
// 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請求設(shè)置
安裝axios
npm install axios
配置request請求
在src
下新建utils/request.js
,request.js
內(nèi)容如下:
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
}
]
})
執(zhí)行命令
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.
出現(xiàn)跨域問題窃判。
七、解決跨域問題
在項目目錄下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/"' //此次填寫生產(chǎn)環(huán)境域名
}
在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 多環(huán)境配置
參考如下:
九询件、將index.html
轉(zhuǎn)移到src
下
原index.html
位置
將
index.html
轉(zhuǎn)移到src
下轉(zhuǎn)移后需要修改build/webpack.dev.conf.js
new HtmlWebpackPlugin({
filename: 'index.html',
template: './src/index.html',
inject: true
}),
轉(zhuǎn)移后還需要修改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'
}),