1创建vue项目
0 先安装nodejs
1 全局安装vue-cli(npm uninstall vue-cli -g删除再次安装就会安装最新的)
npm install --global vue-cli
或(cnpm install --global vue-cli)
cnpm需先安装淘宝镜像 npm install -g cnpm --registry=https://registry.npm.taobao.org
2 cd + 你想安装的路径
例如:cd /Users/liuxiaofei/Desktop/Total/work/web
3 安装初始项目vue init webpack+名称(注vue create是vue自带的创建方式 和 vue init webpack是选择webpack版本进行创建)
vue init webpack mypropost
后面会显示:
? Project name demo_project
? Project description test
? Author 刘晓飞 <>
? Vue build standalone
? Install vue-router? Yes
? Use ESLint to lint your code? No //后续要装,现在不装因为很严格的格式要求
? Set up unit tests No //测试用的,不装
? Setup e2e tests with Nightwatch? No //测试用,不装
? Should we run `npm install` for you after the project has been created? (recom
mended) npm
4 cd进项目
cd mypropost
5 安装所有依赖
npm install
6 运行vue项目
npm run dev
本地运行dist的教程
https://blog.youkuaiyun.com/weixin_41257563/article/details/98875202
2vue项目常用插件
1 axios
为什么要用axios?
axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,它本身具有以下特征:
- 从浏览器中创建 XMLHttpRequest
- 从 node.js 发出 http 请求
- 支持 Promise API
- 拦截请求和响应
- 转换请求和响应数据
- 取消请求
- 自动转换JSON数据
- 客户端支持防止CSRF/XSRF
//安装
npm install axios --save
//在main.js中引入
import axios from 'axios'
//再main.js获取axios对象
Vue.prototype.axios = axios
//在main.js添加可以全局设置,之后就可以不用填域名头和请求头
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
// 在main.js添加可以全局拦截器
// 添加请求拦截器
axios.interceptors.request.use(function (config) {
// 在发送请求之前做些什么
return config;
}, function (error) {
// 对请求错误做些什么
return Promise.reject(error);
});
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
// 对响应数据做点什么
return response;
}, function (error) {
// 对响应错误做点什么
return Promise.reject(error);
});
注意:
axios的post请求只接收form-data格式
1 form-data格式:
就是http请求中的multipart/form-data,它会将表单的数据处理为一条消息,以标签为单元,用分隔符分开.既可以上传键值对,也可以上传文件.当上传的字段是文件时会有Content-Type来表名文件类型;content-disposition用来说明字段的一些信息;
由于有boundary隔离,所以multipart/form-data既可以上传文件也可以上传键值对,它采用了键值对的方式,所以可以上传多个文件.
如:?name=iwen&age=20
2 x-www-form-urlencoded格式:
就是application/x-www-from-urlencoded,会将表单内的数据转换为键值对,比如 : name=Java&age = 23
如:{name:“iwen”,age:20}
axios取消接口请求
axios 提供了一个 CancelToken的函数,这是一个构造函数,该函数的作用就是用来取消接口请求的
例如:
var CancelToken = axios.CancelToken
// 配置发送请求拦截器
http.interceptors.request.use(config => {
config.cancelToken = store.source.token
return config
}, err => {
return Promise.reject(err)
})
router.beforeEach((to, from, next) => {
const CancelToken = axios.CancelToken
store.source.cancel && store.source.cancel()
store.source = CancelToken.source()
next()
})
// 全局变量
store = {
source: {
token: null,
cancel: null
}
}
2 qs
qs是vue项目自带,无需安装,但要引入
//可以在main.js内全局引入和获取对象
import qs from 'qs'
Vue.prototype.qs = qs
qs是用来做序列化的,JSON.stringify也是做序列化处理的,但你要知道他们序列化的结果是不一样的。
var a = {b:1,c:2}
qs-->"b=1&c=2"(这个叫query字符串吗)
JSON.stringify: {"b":1,"c":2}(json字符串)
3element
//下载
npm i element-ui -S
//按需引用需要使用到的组件
npm install babel-plugin-component -D
//然后,修改.babelrc ,将下面加入到plugins对象的最后一个参数中:(根据element文档来,可能有更新)
[
"component",
{
"libraryName": "element-ui",
"styleLibraryName": "theme-chalk"
}
]
//按需引入要用的模块,可直接放在main.js,模块名参考element文档
import { Button, Select } from 'element-ui';
//使用,可直接放在main.js
Vue.use(Button)
//路径2:全局引入
import ElementUI from 'element-ui' //手动变红
import '../node_modules/element-ui/lib/theme-chalk/index.css' //手动变红
Vue.use(ElementUI)
element组件的注意点
<el-table ref="multipleTable" @selection-change="handleSelectionChange" :data="tableData">
<el-table-column
type="selection"
width="55">
</el-table-column>
</el-table>
//方法handleSelectionChange即可获取所选择的选项
handleSelectionChange(val) {
let ids = [];
val.forEach(function(element) {
ids.push(element.id);
});
ids = ids.join(",");
this.multipleSelection = ids;
},
element-ui 下拉el-dropdown-item添加点击事件@click无效,用@click.native
<el-dropdown-item @click.native="handleEditPassword">修改密码</el-dropdown-item>
Element-Layout 布局
xs sm md lg xl五个尺寸的默认值均为24,意味着,任何一个尺寸属性不设置,则该尺寸下响应式宽度为24,这与bootstrap不同
通过基础的 24 分栏,迅速简便地创建布局。
<el-row>
<el-col :span="24">插入内容</el-col>
</el-row>
<el-row>
<el-col :span="12">插入内容</el-col>
<el-col :span="12">插入内容</el-col>
</el-row>
注:
element的rules功能
el-form-item的prop和form表单里面的v-model里面名字一样才有效校验
双层校验放2个对象进rules的对象内
4less
//安装less
npm install --save-dev less less-loader
//配置less: 路径:build---webpack.base.conf.js的module对象添加
{
test: /\.less$/,
loader: "style-loader!css-loader!less-loader"
}
//使用,在要使用的页面的style加
lang = "less"
注意点
less自带媒体查询,可根据屏幕宽度自适应
@media screen{
@media (max-width:768px){
.loginwin{
width:80%;
height: 80%;
}
}
@media (min-width:768px){
.loginwin{
width: 20%;
height: 20%;
}
}
}
5vuex
vuex相当于设置全局变量,而且也是可以实时多个页面数据共享
如果只传一个值,完全可以不用vuex(太浪费),可这样
//main.js中注册Vue时添加变量
new Vue({
el: '#app', router, store,
template: '<App/>',
components: {
App
},
data () {
return {
modoleType: modoleType //初始化modoleType
}
}
//其它页面这样调用
console.log(this.$root.$data.modoleType);
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式
这个状态自管理应用包含以下3个部分:
state,驱动应用的数据源;
view,以声明方式将 state 映射到视图;
actions,响应在 view 上的用户输入导致的状态变化。
//安装
npm install vuex --save
//引入
import Vuex from 'vuex'
//使用
Vue.use(Vuex)
//main.js创建一个store仓库
const store = new Vuex.Store({
state:{ //每一个 Vuex 应用的核心就是 store(仓库)。“store”基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。
count:10
},
mutations:{ //更改 Vuex 的 store 中的状态的唯一方法是提交 mutation
increment(state){
state.count++;
}
}
});
//记得创建Vue实例时引入store
new Vue({
el: '#app',
router,
store, //必须放进实例中
components: { App },
template: '<App/>'
})
//其它页面就可以调用了
this.$store.commit('increment') //其它页面调用store的mutation内方法,必须用.commit();
return this.$store.state.count; //其它页面调用store的state属性
main.js创建一个同级目录store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
//创建一个store仓库
export default new Vuex.Store({
state:{ //每一个 Vuex 应用的核心就是 store(仓库)。“store”基本上就是一个容器,它包含着你的应用中大部分的状态 (state)。
count:10
},
mutations:{ //更改 Vuex 的 store 中的状态的唯一方法是提交 mutation,必须是同步操作,//没有网络请求和其它异步操作可以直接用mutations
increment(state){
state.count++;
},
decrease(state){
state.count--;
}
},
//Action 类似于 mutation,不同在于:
//1 Action 提交的是 mutation,而不是直接变更状态。
//2 Action 可以包含任意异步操作。
actions:{ //有网络请求必须用actions,要异步嘛
increment(context){ //可以设置名称和mutations对应的方法相同的名称
context.commit("increment");
},
decrease(context){ //可以包含任意异步操作。
setTimeout(()=>{
context.commit('decrease');
},1000);
//context.commit('decrease');
}
},
getters:{ //对state数据进行计算,Vuex 允许我们在 store 中定义“getter”(可以认为是 store 的计算属性)。就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算。
getState(state){
return state.count>0?state.count:0;
}
}
});
然后在main.js引用和在实例引用
import store from './store'
new Vue({
el: '#app',
router,
store, //必须放进实例中
components: { App },
template: '<App/>'
})
其它页面调用数据demo
<template>
<div class="hello">
<button @click="geta">+</button>
{{getc}}
<button @click="getb">-</button>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
},
methods:{
geta(){
console.log(111);
this.$store.dispatch('increment');
},
getb(){
console.log(222);
this.$store.dispatch('decrease');
}
},
computed:{
getc(){
this.$store.commit('decrease');
this.$store.commit('increment') //其它页面调用store的mutation内方法,必须用.commit();
//return this.$store.state.count; //其它页面调用store的state属性
return this.$store.getters.getState; //
}
}
}
</script>
6vux
vux需要注意点击按钮的触发要用@click.native,只用@click触发不了
<x-button class="xbuttonView1" @click.native="greet()">下一步</x-button>
//用v-for="(item, key) in timeValue"循环,用:id="key" :value="item"绑定index和值,:key="item.index"绑定key
<checker class="checkerView" v-model="value7" default-item-class="demo2-item" v-for="(item, key) in timeValue" :key="item.index">
<checker-item :id="key" :value="item" @click.native="changeTime">{{item}}</checker-item>
</checker>
7uuid 生产随机码
//安装
npm install uuid --save
//main.js引入
import uuid from 'uuid/v1'
//向Vue对象添加uuid的属性和方法
Vue.prototype.uuid = uuid
//其它页面使用方法
this.uuid()
8vee-validate 表单验证
//安装
npmpm installnst vee-validate --save
//main.js引入
import VeeValidate from 'vee-validate';
//使用
Vue.use(VeeValidate);
//demo,其它页面直接使用,v-validate指定,必须有name做绑定
<input v-validate="'required|email'" name="email" type="text">
<span>{{ errors.first('email') }}</span>
8vue-quill-editor 富文本编辑器及插入图片自定义
//1.安装
npm install vue-quill-editor --save
//2在main.js中引入
import VueQuillEditor from 'vue-quill-editor'
import 'quill/dist/quill.core.css'
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
Vue.use(VueQuillEditor);
//3其它页面直接使用
<template>
<div>
<div class="richTextView">
<!-- 图片上传组件辅助-->
<el-upload class="avatar-uploader" :action="serverUrl" name="img" :headers="header" :show-file-list="false" :on-success="uploadSuccess" :on-error="uploadError" :before-upload="beforeUpload">
</el-upload>
<quill-editor v-model="content" ref="myQuillEditor" :options="editorOption" @change="onEditorChange($event)">
</quill-editor>
</div>
</div>
</template>
<script>
const toolbarOptions = [
['bold', 'italic', 'underline', 'strike'], // toggled buttons
[{
'header': 1
}, {
'header': 2
}], // custom button values
[{
'list': 'ordered'
}, {
'list': 'bullet'
}],
[{
'indent': '-1'
}, {
'indent': '+1'
}], // outdent/indent
[{
'direction': 'rtl'
}], // text direction
[{
'size': ['small', false, 'large', 'huge']
}], // custom dropdown
[{
'header': [1, 2, 3, 4, 5, 6, false]
}],
[{
'color': []
}, {
'background': []
}], // dropdown with defaults from theme
[{
'font': []
}],
[{
'align': []
}],
['link', 'image'],
['clean']
]
export default {
data() {
return {
quillUpdateImg: false, // 根据图片上传状态来确定是否显示loading动画,刚开始是false,不显示
content: null,
editorOption: {
placeholder: '',
theme: 'snow', // or 'bubble'
modules: {
toolbar: {
container: toolbarOptions,
handlers: {
'image': function(value) {
if(value) {
// 触发input框选择图片文件
document.querySelector('.avatar-uploader input').click()
} else {
this.quill.format('image', false);
}
}
}
}
}
},
serverUrl: '/manager/common/imgUpload', // 这里写你要上传的图片服务器地址
header: {
// token: sessionStorage.token
} // 有的图片服务器要求请求头需要有token
}
},
methods: {
onEditorChange({
editor,
html,
text
}) { //内容改变事件
console.log("---内容改变事件---")
this.content = html
console.log(html)
},
// 富文本图片上传前
beforeUpload() {
// 显示loading动画
this.quillUpdateImg = true
},
uploadSuccess(res, file) {
// res为图片服务器返回的数据
// 获取富文本组件实例
console.log(res);
let quill = this.$refs.myQuillEditor.quill
// 如果上传成功
if(res.code == 200) {
// 获取光标所在位置
let length = quill.getSelection().index;
// 插入图片 res.url为服务器返回的图片地址
quill.insertEmbed(length, 'image', res.url)
// 调整光标到最后
quill.setSelection(length + 1)
} else {
this.$message.error('图片插入失败')
}
// loading动画消失
this.quillUpdateImg = false
},
// 富文本图片上传失败
uploadError() {
// loading动画消失
this.quillUpdateImg = false
this.$message.error('图片插入失败')
}
}
}
</script>
<style>
.ql-editor.ql-blank, .ql-editor {
height: 350px;
}
.richTextView{
margin: 20px;
width: 100%;
}
</style>
9Vue-Awesome-Swiper 轮播图()各种特效
获取案例的官方案例库
https://surmon-china.github.io/vue-awesome-swiper/
把案例里的<md-card>等奇奇怪怪的标签都换成<div>即可完美运行
//安装
npm install vue-awesome-swiper --save
//main.js全局引入
import VueAwesomeSwiper from 'vue-awesome-swiper'
import 'swiper/dist/css/swiper.css'
Vue.use(VueAwesomeSwiper, /* { default global options } */)
//在其它页面直接使用
<template>
<div>
<div class="swiper-inner">
<!-- swiper -->
<swiper :options="swiperOption">
<swiper-slide>
<img class="imgH" src="./bg.png" />
</swiper-slide>
<swiper-slide>
<img class="imgH" src="./bg.png" />
</swiper-slide>
<swiper-slide>
<img class="imgH" src="./bg.png" />
</swiper-slide>
<swiper-slide>
<img class="imgH" src="./bg.png" />
</swiper-slide>
</swiper>
</div>
</div>
</template>
<script>
export default {
data() {
return {
swiperOption: {
effect: 'coverflow',
grabCursor: true,
centeredSlides: true,
slidesPerView: 'auto',
coverflowEffect: {
rotate: 50,
stretch: 0,
depth: 100,
modifier: 1,
slideShadows : true
},
pagination: {
el: '.swiper-pagination'
}
}
}
}
}
</script>
<style scoped>
.imgH{
width: 300px;
height: 600px;
}
.swiper-inner {
width: 100%;
height: 400px;
padding-top: 50px;
padding-bottom: 50px;
-webkit-user-select: none;/*禁用手机浏览器的用户选择功能 */
-moz-user-select: none;
}
.swiper-slide {
background-position: center;
background-size: cover;
width: 300px;
height: 600px;
}
10 vue引入jssdk
//安装
npm install weixin-js-sdk --save
//引入
import wx from 'weixin-js-sdk'
//mounted内配置(不一定在此生命周期)
mounted(){
var that = this;
let url = location.href.split('#')[0]; //获取锚点之前的链接
that.$ajax.novpost('callback/getWxSignature',{url:url}).then(res=>{
console.log(res);
wx.config({
debug: false,
appId: "wx3175622fed04b127",
timestamp: res.timestamp,
nonceStr: res.nonceStr,
signature: res.signature,
jsApiList: ['chooseImage','getLocalImgData'] //引入要用的功能名称
});
wx.ready(function(){
// config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。
});
})
},
//其它方法内直接使用
uploadImg(){
var that = this;
wx.chooseImage({
count: 1, // 默认9
sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
success: function (res) {
var localId = res.localIds[0]; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
wx.getLocalImgData({
localId: localId, // 图片的localID
success: function (res) {
//alert(res.localData); // localData是图片的base64数据,可以用img标签显示
console.log(res.result);
// that.imgUrl = res.localData;
that.uploaderImg(res.localData);
}
});
}
});
},
11 md5加密
npm安装:
npm install --save js-md5
1.在需要使用的项目文件中引入:
import md5 from 'js-md5';
使用:
md5('holle') // bcecb35d0a12baad472fbe0392bcc043
2.或者在main.js文件中将md5转换成vue原型:
import md5 from 'js-md5';
Vue.prototype.$md5 = md5;
在需要用到的文件中使用:
this.$md5('holle') // bcecb35d0a12baad472fbe0392bcc043
12store保存本地
cnpm install store
在需要用到的地方引入
import store from ‘store’
设置
store.set(‘userInfo’, res.data.outData);
提取
store.get(‘user’)
13aes加密
npm install crypto-js --save
在项目中新建一个utils.js文件
/**
* 工具类
*/
import Vue from 'vue'
import CryptoJS from 'crypto-js'
export default {//加密
encrypt(word, keyStr){
keyStr = keyStr ? keyStr : '16BytesLengtdcba';//abcdefgabcdefg12
var key = CryptoJS.enc.Utf8.parse(keyStr);//Latin1 w8m31+Yy/Nw6thPsMpO5fg==
var srcs = CryptoJS.enc.Utf8.parse(word);
var encrypted = CryptoJS.AES.encrypt(srcs, key, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
return encrypted.toString();
},
//解密
decrypt(word, keyStr){
keyStr = keyStr ? keyStr : '16BytesLengtdcba';//abcdefgabcdefg12
var key = CryptoJS.enc.Utf8.parse(keyStr);//Latin1 w8m31+Yy/Nw6thPsMpO5fg==
var decrypt = CryptoJS.AES.decrypt(word, key, {mode:CryptoJS.mode.ECB,padding: CryptoJS.pad.Pkcs7});
return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}
}
14 使用vue-echarts
https://ecomfe.github.io/echarts-doc/public/cn/tutorial.html 官方文档
1安装:
cnpm install vue-echarts --save
2//echarts按需引入 (main.js)
import ECharts from 'vue-echarts/components/ECharts'
import 'echarts/lib/chart/line'
import 'echarts/lib/chart/pie'
import 'echarts/lib/chart/bar'
import 'echarts/lib/component/tooltip'
import 'echarts/lib/component/polar'
import 'echarts/lib/component/legend'
import 'echarts/lib/component/title.js'
Vue.component('chart', ECharts)
3vue单文件直接用
<template>
<div class="hello">
<chart ref="chart1" :options="orgOptions" :auto-resize="true"></chart>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
data () {
return {
orgOptions: {},
}
},
mounted() {
this.orgOptions = {
xAxis: {
type: 'category',
data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
},
yAxis: {
type: 'value'
},
series: [{
data: [820, 932, 901, 934, 1290, 1330, 1320],
type: 'line',
smooth: true
}]
}
}
}
</script>
15 vue-ls
用于从Vue上下文中使用本地存储,会话存储和内存存储
https://www.npmjs.com/package/vue-ls
3注意点
1请求跨域问题解决(可通过CMD命令ipconfig 查看MAC地址)
1/config/index.js的proxyTable对象内加相应跨域信息
'/SSMSC': {
target: 'http://192.168.31.161:80/SSMSC',//设置你调用的接口域名和端口号 别忘了加http
changeOrigin: true,
pathRewrite: {
'^/SSMSC': '/SSMSC'//这里理解成用‘/SSMSC’代替target里面的地址,后面组件中我们掉接口时直接用api代替 比如我要调用'http://40.00.100.100:3002/user/add',直接写‘/SSMSC/user/add’即可
}
}
2在main.js内添加host
//如果不用HOST可不设置,下面例子使用了HOST
Vue.prototype.HOST = "/SSMSC"
3上面2步即配置完成
在其它页面调用this.HOST即可直接使用
//此url也可直接设置为路由形式"/SSMSC/subscription/newDrug"路由会自动填头部链接
var url = this.HOST + "/subscription/newDrug";
this.axios.post(url, this.qs.stringify({
drug_name: this.form.drug_name
}), {
headers: {'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8'}
})
.then(res => {
this.show2 = true;
})
2vue的过滤效果
Vue.js 允许你自定义过滤器,可被用于一些常见的文本格式化。过滤器可以用在两个地方:双花括号插值和 v-bind 表达式 (后者从 2.1.0+ 开始支持)。过滤器应该被添加在 JavaScript 表达式的尾部,由“管道”符号指示:
//在双花括号中
{{ message | capitalize }}
//与data同级
filters: {
capitalize: function (value) {
if (!value) return ''
value = value.toString()
return value.charAt(0).toUpperCase() + value.slice(1)
}
}
//也可以在main.js里全局配置过滤器
Vue.filter('capitalize', function (value) {
if (!value) return ''
value = value.toString()
return value.charAt(0).toUpperCase() + value.slice(1)
})
3router配置
//主要在src\router\index.js中配置路由,先引入地址
import IntegralManagement from '@/components/IntegralManagement/IntegralManagement'
//再在router里面配置信息
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},{
path: '/IntegralManagement',
name: 'IntegralManagement',
component: IntegralManagement
}
]
//配置完后可调用下语句直接跳转页面
this.$router.push('/IntegralManagement')
//也可使用 <router-link> 映射路由
<router-link to="/IntegralManagement">IntegralManagement</router-link>
4钩子函数与methods:{}同级
mounted(){} (每次进入页面都会调用)
created(){} (只会在第一次创建调用)
5vue js跳转页面
this.$router.push(’/addMedicationReminder’);
6vue项目判断机型做响应式
judgeComment() {
//获取机器型号
let sUserAgent = navigator.userAgent.toLowerCase();
//开始定义和匹配
let bIsIpad = sUserAgent.match(/ipad/i) == "ipad";
let bIsIphoneOs = sUserAgent.match(/iphone os/i) == "iphone os";
let bIsMidp = sUserAgent.match(/midp/i) == "midp";
let bIsUc7 = sUserAgent.match(/rv:1.2.3.4/i) == "rv:1.2.3.4";
let bIsUc = sUserAgent.match(/ucweb/i) == "ucweb";
let bIsAndroid = sUserAgent.match(/android/i) == "android";
let bIsCE = sUserAgent.match(/windows ce/i) == "windows ce";
let bIsWM = sUserAgent.match(/windows mobile/i) == "windows mobile";
//输出匹配结果,分为phone和pc,2种
console.log("您的浏览设备为:");
if (bIsIpad || bIsIphoneOs || bIsMidp || bIsUc7 || bIsUc || bIsAndroid || bIsCE || bIsWM) {
console.log("phone");
} else {
console.log("pc");
}
},
7html内可直接数据处理
{{item.iphone.slice(0, 3)}}
8可修改直接build生成的文件夹名称
在config文件夹下面的index.js
修改路径,就能生成其他文件夹名字啦
9Vue打包上线部署
注意点1:
在打包前还要在config文件夹中的index.js中设置一个路径问题,不然会报错,在js中找到build:{assetsPublicPath:’/’},默认路径是‘/’,需要加上’.’,写成、’./’(一般正常编辑代码是只进行本步修改即可)。
注意点2:
背景图相对路径会报错找不到,要先上传图片,用线上图片展示
background-image: url(‘http://jinronghtml.vilicom.cn/upload/4wgz.png’);
build: {
// Template for index.html
index: path.resolve(__dirname, '../finamini/index.html'),
// Paths
assetsRoot: path.resolve(__dirname, '../finamini'),
assetsSubDirectory: 'static',
assetsPublicPath: './',
10computed中不能写异步请求
computed本来就是用来返回计算后的值得,是需要马上得到的,而不是要等一段时间才能得到的
11
钩子函数可用async定义异步钩子,内部可用await等待接口返回的结果再赋值
async mounted(){
const {status, data:{ user }} = await this.$axios.get('/users/getUser');
if(status === 200) {
this.user = user;
}
}
12Vue设置左上角icon图标
1)、提前把icon图标copy到static目录下
(2)、在index.html页面添加 <link rel ="shortcut icon" type="image/x-icon" href="static/favicon.ico">
13理解 babel之配置文件.babelrc 基本配置项
https://www.cnblogs.com/tugenhua0707/p/9452471.html
14.editorconfig文件
EditorConfig帮助开发人员在不同的编辑器和IDE之间定义和维护一致的编码样式。
https://www.cnblogs.com/xieqian/p/10045610.html
15vue
r
e
f
s
的
基
本
用
法
一
般
来
讲
,
获
取
D
O
M
元
素
,
需
d
o
c
u
m
e
n
t
.
q
u
e
r
y
S
e
l
e
c
t
o
r
(
"
.
i
n
p
u
t
1
"
)
获
取
这
个
d
o
m
节
点
,
然
后
在
获
取
i
n
p
u
t
1
的
值
。
但
是
用
r
e
f
绑
定
之
后
,
我
们
就
不
需
要
在
获
取
d
o
m
节
点
了
,
直
接
在
上
面
的
i
n
p
u
t
上
绑
定
i
n
p
u
t
1
,
然
后
refs的基本用法 一般来讲,获取DOM元素,需document.querySelector(".input1")获取这个dom节点,然后在获取input1的值。 但是用ref绑定之后,我们就不需要在获取dom节点了,直接在上面的input上绑定input1,然后
refs的基本用法一般来讲,获取DOM元素,需document.querySelector(".input1")获取这个dom节点,然后在获取input1的值。但是用ref绑定之后,我们就不需要在获取dom节点了,直接在上面的input上绑定input1,然后refs里面调用就行。
然后在javascript里面这样调用:this.$refs.input1 这样就可以减少获取dom节点的消耗了
<div id="app">
<input type="text" ref="input1"/>
<button @click="add">添加</button>
</div>
<script>
new Vue({
el: "#app",
methods:{
add:function(){
this.$refs.input1.value ="22"; //this.$refs.input1 减少获取dom节点的消耗
}
}
})
</script>
16全局变量process.env
扒一扒process.env
process对象是全局变量,它提供当前node.js的有关信息,以及控制当前node.js的有关进程。因为是全局变量,它对于node应用程序是始终可用的,无需require()。
既然process都是一个对象了,env自然是它的一个属性,这个属性返回包含用户环境信息的对象。在终端输入node后,在输入process.env可以看到打印出来的信息。
主角出场 process.env.NODE_ENV
NODE_ENV不是process.env对象上原有的属性,它是我们自己添加上去的一个环境变量,用来确定当前所处的开发阶段。一般生产阶段设为production,开发阶段设为develop,然后在脚本中读取process.env.NODE_ENV。
17本地预览打包后的dist
dist 目录需要启动一个 HTTP 服务器来访问 (除非你已经将 publicPath 配置为了一个相对的值),所以以 file:// 协议直接打开 dist/index.html 是不会工作的。在本地预览生产环境构建最简单的方式就是使用一个 Node.js 静态文件服务器,例如 serve
npm install -g serve
# -s 参数的意思是将其架设在 Single-Page Application 模式下
# 这个模式会处理即将提到的路由问题
serve -s dist
4推荐测试软件
//在Linux/Mac 下 需要先给执行权限
chmod a+x natapp
//然后再运行
./natapp
//用管理员权限编辑
sudo vi config.ini
//修改后
Esc 退出编辑模式,输入以下命令:
:wq 保存后退出vi,若为 :wq! 则为强制储存后退出(常用)
:w 保存但不退出(常用)
:w! 若文件属性为『只读』时,强制写入该档案
:q 离开 vi (常用)
:q! 若曾修改过档案,又不想储存,使用 ! 为强制离开不储存档案。
:e! 将档案还原到最原始的状态!
//最后vue项目想内网穿透
在webpack.dev.conf.js中添加:disableHostCheck: true
//如下
devServer: {
public: 'local.kingsum.biz',
clientLogLevel: 'warning',
historyApiFallback: true,
hot: true,
compress: true,
host: HOST || config.dev.host,
port: PORT || config.dev.port,
open: config.dev.autoOpenBrowser,
overlay: config.dev.errorOverlay
? { warnings: false, errors: true }
: false,
publicPath: config.dev.assetsPublicPath,
proxy: config.dev.proxyTable,
quiet: true, // necessary for FriendlyErrorsPlugin
watchOptions: {
poll: config.dev.poll,
},
disableHostCheck: true //加上这段
}