安装
- 前提: 安装 nodejs / git
- 安装 cli3:
npm i @vue/cli -g
或yarn global add @vue/cli
(需要安装 yarn/cnpm 等)
如果报错:
- 试试 npm 安装
- https://www.jianshu.com/p/9308e6abbe44
创建项目
-
创建:
vue create 项目名
||vue create .
当前目录 -
选择
Manually select features
(手动配置),方向键切换,空格选取,回车确定bable
css 预处理,选择 node sass
In dedicated config files
- 是否保存配置项:
n
-
项目创建成功后,有提示信息,提示中的
npm run serve
是serve
不是 server,曾折腾好几个小时,就因多个r
同一台电脑不兼容两个版本,如果需要两个版本同时存在,请安装调节工具:npm i @vue/cli-init -g
安装 cli2:
npm i vue-cli -g
-
创建完整版项目:
vue init webpack 项目名
? Project name mycli2
确认项目名称,回车Project description (A Vue.js project)
回车Author ()
信息- 回车
Install vue-router?
是否用路由Use ESLint to lint your code? (Y/n)
键入nSet up unit tests (Y/n)
键入nSetup e2e tests with Nightwatch? (Y/n)
键入n- 选择安装源:
NPM YARN 自己搞
-
创建简化版项目:
vue init webpack-simple 项目名
- 键入项目名
- 三次回车
- 是否使用
sass
创建完成后根据提示信息操作
yarn 解决速度慢问题
npm i yarn -g
安装yarnyarn -v
有提示说明安装成功yarn config set registry https://registry.npm.taobao.org
切换为国内镜像yarn config get registry
查看当前源yarn global add @vue/cli
使用 yarn 安装 vue-cli3
vue create .
默认安装方式更改(npm or yarn)
https://www.cnblogs.com/saysmy/p/10064573.html
https://cli.vuejs.org/zh/guide/creating-a-project.html#vue-create
vim ~/.vuerc
E325: ATTENTION
Found a swap file by the name "~/.vuerc.swp"
owned by: jinyunfei dated: Wed Sep 25 10:07:09 2019
file name: ~jinyunfei/.vuerc
modified: YES
user name: jinyunfei host name: jindeMacBook-Pro.local
process ID: 1572
While opening file "/Users/jinyunfei/.vuerc"
dated: Thu Oct 24 17:24:13 2019
NEWER than swap file!
(1) Another program may be editing the same file. If this is the case,
be careful not to end up with two different instances of the same
file when making changes. Quit, or continue with caution.
(2) An edit session for this file crashed.
If this is the case, use ":recover" or "vim -r /Users/jinyunfei/.vuerc"
to recover the changes (see ":help recovery").
If you did this already, delete the swap file "/Users/jinyunfei/.vuerc.swp"
to avoid this message.
Swap file "~/.vuerc.swp" already exists!
[O]pen Read-Only, (E)dit anyway, (R)ecover, (D)elete it, (Q)uit, (A)bort:
一堆提示,按 E 直接编辑
node-sass 安装报错
vim ~/.vuerc
-"useTaobaoRegistry": false
(测试有效)npm install chromedriver --chromedriver_cdnurl=http://cdn.npm.taobao.org/dist/chromedriver
(未测)npm rebuild node-sass
||npm rebuild node-sass --force
(未测)yarn config set sass_binary_site http://cdn.npm.taobao.org/dist/node-sass -g
| 可能解决 node-sass 报错 (未测)- node-sass 报错:https://blog.csdn.net/weixin_42406046/article/details/80604623 (未测)
目录结构
public 静态资源( 相当于cli 2.x中的 static 文件夹,放第三方压缩好的js或其他 )
images
assets 静态资源 放需要进行压缩打包的文件
- css
--- reset.css
- images
--- logo.jpg
- font
components
--- common( 全局公共组件 )
views
router
store
--- index.js
--- module
utils
--- 自定义插件
--- 第三方插件
--- 自定义封装模块
--- 不能被模块化引入的
filter
...
关于静态资源处理
通过 npm 装包
- 全局注册插件时,
import xx form 'xx'
后经常在vue.use()
和vue.prototype.$xxx
中来回使用,其中有什么差别?
简单的来说,Vue.use() 方法要求引入的是一个函数,或者包含 init 方法的对象,引入为一个对象但没有 init 方法,就不能使用 Vue.use() 方法,必须挂在在 Vue 的原型对象上,才可以全局使用
Vue.js 要求插件作为对象时必修暴露 install 方法,如果插件是一个函数,它会被作为 install 方法。install 方法调用时,会将 Vue 作为参数传入
Vue.js 官方提供的一些插件 (例如 vue-router) 在检测到 Vue 是可访问的全局变量时会自动调用 Vue.use()。然而在像 CommonJS 这样的模块环境中,你应该始终显式地调用 Vue.use():
用 Browserify 或 webpack 提供的 CommonJS 模块环境时
var Vue = require('vue')
var VueRouter = require('vue-router')
不要忘了调用此方法
Vue.use(VueRouter)
- 局部注册
var xx = require( path )
数据通讯:vue-cli 中使用 axios, fetch 和反向代理
axiso封装:https://juejin.im/post/5b55c118f265da0f6f1aa354
axios
-
安装:
npm i axios -D
-
或cdn引入:
<script src="https://cdn.bootcss.com/axios/0.19.0-beta.1/axios.js"></script>
后暴漏出一个axios
对象,调用后返回promise
对象
一般在main.js
引入axios
后需要在Vue.prototype
上挂载,解决单个组件重复import axios from 'axios'
问题
main.js:
import axios from 'axios'
Vue.prototype.$http = axios
get
axios({
url:'',
method:'get', // 默认get方式 可以不写这一项
// post方式用data get方式用params
params:{
key : vaule
}
})
.then(res=>{console.log(res)})
.catch(err=>{throw err})
如果没有参数的get方式
axios(url).then()
post
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
let params = new URLSearchParams();
params.append('a': 1);
params.append('b': 2);
axios({
url: '',
method: 'post',
// post传参为data
data: params
})
.then(res => { console.log(res) })
.catch(err => { throw err })
post
坑:跨域报错
解决方式:
- 在
new Vue
之前统一设置请求头
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
- 使用
URLSearchParams
实例化params
对象
let params = new URLSearchParams()
- 使用
params .append()
方法添加参数
params.append(key,value);
params.append(key2,value2)
axios的请求默认的headers的Content-Type为’application/x-www-form-urlencoded;charset=UTF-8’
post请求后端的 (后端框架ssm)Controller中@RequestParam取不到请求参数
这个时候对请求参数做qs.stringify()处理就好了或者要求后端改成从@RequestBody获取参数也成
当请求头部为application/json 无需对请求参数做任何处理
response 响应拦截器主要是对请求超时的情况做处理。
完整代码
<script src="https://cdn.bootcss.com/axios/0.19.0-beta.1/axios.js"></script>
<script>
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
let params = new URLSearchParams();
params.append('a', 1);
params.append('b', 2);
new Vue({
el: '#app',
methods: {
get() {
axios({
url: '',
method: 'get', // 默认get可以不写
// get方式用params
params: {
key: vaule
}
})
.then(res => { console.log(res) })
.catch(err => { throw err })
},
post() {
axios({
url: '',
method: 'post',
// post传参为data
data: params
})
.then(res => { console.log(res) })
.catch(err => { throw err })
}
}
})
</script>
跨域问题
前端:反向代理,JSONP
后端:设置请求头header('Access-Control-Allow-Origin:*')
https://blog.csdn.net/yuanlaijike/article/details/80522621
axios的跨域问题
反向代理
项目根目录新建vue.config.js
配置如下
vue.config.js
默认可以直接使用 http-proxy-middleware
中间件
module.exports = {
devServer: {
proxy: {
'/duitang': {
target: 'https://www.duitang.com',
changeOrigin: true,
pathRewrite: {
// 这里的 ^ 目的是可能出现多个/duitang 我们只替换第一个
'^/duitang': ''
}
}
}
}
}
main.js
配置如下
import Vue from 'vue'
import App from './App.vue'
import router from './router'
引入axios对象
import axios from 'axios'
将axios设置为全局
Vue.prototype.$http = axios
Vue.config.productionTip = false
new Vue({
router,
render: h => h(App),
}).$mount('#app')
.vue
文件配置如下
export default {
name: "app",
components: {},
created(){
this.$http.get("/duitang/napi/index/groups/?app_version=14&app_code=mdt")
.then(res => {console.log(res)})
.catch(err => {console.log(err)})
}
};
至此,反向代理成功,可以拿到数据
路径别名
https://segmentfault.com/a/1190000016135314
注意在 vue-cli 3.x ,/node_modules/@vue/cli-service/lib/config/base.js
已经配好了 @
路径,代表 src
目录
测试成功:
// vue.config.js
module.exports = {
configureWebpack: {
resolve: {
alias: {
'assets': '@/assets',
'components': '@/components',
'views': '@/views',
}
}
},
}
这个测试成功
var path = require('path')
function resolve (pathUrl){
return path.resolve(__dirname,pathUrl)
}
module.exports = {
chainWebpack: function ( config ){
config.resolve.alias
.set('Css',resolve('src/assets/css'))
.set('Common',resolve('src/components/common'))
.set('Utils',resolve('src/utils'))
.set('Filters',resolve('src/Filters'))
.set('Pages',resolve('src/components/pages'))
}
}
图片路径问题
成功
css:
.box{
background: url('~@/static/image/right_add.png');
}
https://www.cnblogs.com/s313139232/p/9007228.html
data(){
return{
bacStyle:{
backgroundImage:`url(${require(`../assets/img/about/${this.$route.path == "/about/company" ? 1 : 2}.jpg`)})`
}
}
},
注意:在图片src属性使用路径别名时候,会出错误。解决:`<img src=" ~Assets/img/111.png" >`
注意:在引用 static 文件夹下的图片还是失败,不管是路径别名还是直接写路径测试都不能显示图片
axios拦截器
请求前
axios.interceptors.request.use(function (config) {
// Do something before request is sent
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
请求后
axios.interceptors.response.use(function (response) {
// Do something with response data
return response;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});
封装axios,加载动画
utils 目录下新建 http.js
import axios from 'axios'
import { Indicator } from 'mint-ui';
axios.interceptors.request.use(function (config) {//请求前
Indicator.open({
text: '加载中...',
spinnerType: 'triple-bounce'
})
return config;
}, function (error) {
// Do something with request error
return Promise.reject(error);
});
// Add a response interceptor
axios.interceptors.response.use(function (response) { // 请求后
Indicator.close();
return response;
}, function (error) {
// Do something with response error
return Promise.reject(error);
});
const http = ({ url, method, params, headers }) => {
return new Promise((reslove, reject) => {
axios({
url,
method,
params,
headers
})
.then(res => { reslove(res) })
.catch(err => {
throw err
})
})
}
export default http
Vuex-action.js
引入使用
import * as type from './type'
import http from '@/utils/http'
const actions = {
async getNHot({ commit }, val) {
let result = await http({
url: `/maoyan/ajax/${val}`,
method: 'get',
params,
})
let action = {
type: type.MODIFY_N_HOTS,
payload: result.data
}
commit(action)
}
}
export default actions
vue-resource
解决post报跨域错误:设置提交方式为普通表单数据
this.$http.post(url,{},{
emulateJSON:true
})
打包上线
- npm run build
- 对 dist 目录压缩
- 上传到云服务器对应目录
- 使用 终端 连接云服务器解压
针对 build 后的文件双击 index.html 白屏问题:https://cli.vuejs.org/zh/config/#publicpath
原因:build 后的 publicPath 为 / ,是服务器根目录的路径,造成资源地址错误,加载失败
解决:vue.config.js
module.exports = {
publicPath: './' || ''
}
相对 publicPath 的限制
相对路径的 publicPath 有一些使用上的限制。在以下情况下,应当避免使用相对 publicPath:
当使用基于 HTML5 history.pushState 的路由时;
当使用 pages 选项构建多页面应用时。
Vue 多页
https://cli.vuejs.org/zh/config/#pages
module.exports = {
pages: {
index: {
// page 的入口
entry: 'src/index/main.js',
// 模板来源
template: 'public/index.html',
// 在 dist/index.html 的输出
filename: 'index.html',
// 当使用 title 选项时,
// template 中的 title 标签需要是 <title><%= htmlWebpackPlugin.options.title %></title>
title: 'Index Page',
// 在这个页面中包含的块,默认情况下会包含
// 提取出来的通用 chunk 和 vendor chunk。
chunks: ['chunk-vendors', 'chunk-common', 'index']
},
// 当使用只有入口的字符串格式时,
// 模板会被推导为 `public/subpage.html`
// 并且如果找不到的话,就回退到 `public/index.html`。
// 输出文件名会被推导为 `subpage.html`。
subpage: 'src/subpage/main.js'
}
}