Vue项目总结

Vue 项目搭建


初始化 Vue 项目

  1. 安装全局包 cnpm i vue-cli -g cnpm i cross-env -g :设置项目的环境

  2. 在桌面生成项目 在桌面打开命令:

vue init webpack-simple vue_project(简单版本)

vue init webpack vue_project (完整版)

  1. 切换到项目根目录下安装依赖包 cd vue_project cnpm install

  2. 切换到项目根目录下运行 npm run dev


常见问题 :

项目打包后用服务器打开一片空白 vue / 打包取消生成 map 文件

修改默认的打包路径文件 config\index.js

//46行
build:{
  // Template for index.html
  index: path.resolve(__dirname, '../dist/index.html'),
  // Paths
  assetsRoot: path.resolve(__dirname, '../dist'),
  assetsSubDirectory: 'static',
  assetsPublicPath: './',//46行修改这个 '/' => './'
  ...
 productionSourceMap: false,//49行改为false
}

项目打包后 css 里的背景图片显示不了

?> 修改 css 打包路径文件 build/utils.js

if (options.extract) {
  return ExtractTextPlugin.extract({
    use: loaders,
    fallback: 'vue-style-loader',
    publicPath: '../../' //50行添加这句话
  });
} else {
  return ['vue-style-loader'].concat(loaders);
}

vue 打 Hbuilder 打包 app,设置沉浸式状态栏

?> 在mainfest.jsonplus中以下位置添加statusbar内容

"plus": {
  "statusbar":{
    "immersed": true/*添加沉浸式状态栏*/
  },
  "splashscreen": {
    "autoclose": true,/*是否自动关闭程序启动界面,true表示应用加载应用入口页面后自动关闭;false则需调plus.navigator.closeSplashscreen()关闭*/
  "waiting": true/*是否在程序启动界面显示等待雪花,true表示显示,false表示不显示。*/
},

vue 过滤器

?> 时间戳 1534475169000 => 2018-08-17 11:06:09

Vue.filter('formatTime', function(value) {
  if (!value || value == '') {
    return value;
  } else {
    let date = new Date(value); //如果date为13位不需要乘1000
    let Y = date.getFullYear() + '-';
    let M =
      (date.getMonth() + 1 < 10
        ? '0' + (date.getMonth() + 1)
        : date.getMonth() + 1) + '-';
    let D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
    let h =
      (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
    let m =
      (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) +
      ':';
    let s =
      date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
    return Y + M + D + h + m + s;
  }
});

vue 路由懒加载

?> 时间戳 1534475169000 => 2018-08-17 11:06:09

import Vue from 'vue'; //vue
import VueRouter from 'vue-router'; //路由
import { isLogin } from '@/api/index.js';
import { Notification } from 'element-ui';
Vue.use(VueRouter); //挂载路由

// 定义路由规则
const routes = [
  {
    path: '/',
    component: resolve => require(['@/views/index.vue'], resolve),
    name: '首页',
    children: [
      {
        path: '/login',
        component: resolve => require(['@/views/login.vue'], resolve),
        meta: {
          title: '登录',
          breadcrumb: ['登录']
        }
      }
    ]
  }
];

// 创建新路由对象
const router = new VueRouter({
  routes
});
// 路由校验
router.beforeEach((to, from, next) => {
  // 设置标题
  if (to.meta.title) {
    document.title = to.meta.title;
  }
  next();
});
//导出路由
export default router;

异步输出

function sleep(time) {
  return new Promise(resolve => setTimeout(resolve, time));
}
sleep(3000).then(() => {
  console.log('3秒后输出我');
});

Vue ie 兼容

?> 解决方式:安装 “babel-polyfill” 即可。

//1. 安装 "babel-polyfill"
cnpm install --save-dev babel-polyfill

//2. 在入口main.js文件引入:
import 'babel-polyfill';

//3. 在build文件夹下找到webpack.base.conf.js.    替换第15行内容

entry: {
  app: ["babel-polyfill", "./src/main.js"]
},

vue 路由传参

?> 方案一 需要在 path 中添加/:id 来对应 $router.push 中 path 携带的参数。在子组件中可以使用来获取传递的参数值

this.$router.push({
  path: `/goods/${id}`
});
// router.js
{
  path: '/goods/:id',
  name: 'goods',
  component: goods
}
// 获取
$route.params.id

?> 方案二 父组件中:通过路由属性中的 name 来确定匹配的路由,通过 params 来传递参数。

this.$router.push({
  name: 'Describe',
  params: {
    id: id
  }
})
// router.js
{
  path: '/goods',
  name: 'goods',
  component: goods
}
// 获取
$route.params.id

?> 方案三 父组件:使用 path 来匹配路由,然后通过 query 来传递参数 query 传递的参数会显示在 url 后面?id=?

this.$router.push({
  path: '/describe',
  query: {
    id: id
  }
})
// router.js
{
  path: '/goods',
  name: 'goods',
  component: goods
}
// 获取
$route.query.id

手机输入框获取焦点是软键盘遮挡输入框

window.addEventListener('resize', function() {
  if (
    document.activeElement.tagName == 'INPUT' ||
    document.activeElement.tagName == 'TEXTAREA'
  ) {
    window.setTimeout(function() {
      document.activeElement.scrollIntoViewIfNeeded();
    }, 0);
  }
});

vuex 状态持久化

vuex-persistedstate

// node
cnpm install vuex-persistedstate --save

// store.js
import createPersistedState from 'vuex-persistedstate'
const store = new Vuex.Store({
// ...
  plugins: [createPersistedState()]  //会自动保存创建的状态。刷新还在
})

项目打包 Nginx服务器导致CSS无法解析不起效果

?> 配置Nginx的时候将/etc/nginx/nginx.conf的一行include /etc/nginx/mime.types;误删 导致了Nginx无法正确识别CSS文件,因此向浏览器发送了错误的MIME类型

错误配置

正确配置

移动端兼容

页面上下滚动时卡顿

#app{
  -webkit-overflow-scrolling: touch;
}
body{
  overflow: auto;
  -webkit-overflow-scrolling: touch;
}

移除移动端页面点击延迟

在main.js里引用fastclick

//node
cnpm install fastclick --save
//main.js
const FastClick = require('fastclick')
FastClick.attach(document.body)

移动端下拉 浏览器报错

[Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive. See

body{touch-action: none;}

vue-countupjs 数字跳动插件使用方法

npm : https://www.npmjs.com/package/vue-countupjs

demo

api 注释 默认
tag 外层标签 span
startValue 起始值 0
endValue 结束值 0
duration 动画持续时间 2
delay 延时更新时间 0
immediate 是否立即执行动画 true
animateClass 执行期间动画, 执行后删除,优先级低于animatedClass项
animatedClass 执行前插入, 执行后删除

还有一个 countup配置项

 options:{
  useEasing: true, // 缓动动画 easing
  useGrouping: true, // 1,000,000 vs 1000000
  separator: ',', // 数字分隔符
  decimal: '.', // 小数分隔符
  prefix: '', // 前缀
  suffix: '' // 后缀
}
//node 
cnpm install vue-countupjs --save
//home.vue
<template>
  <div class="home">
      <v-countup :start-value="0" :end-value="100.12345678" :decimals="8" tag="span"></v-countup>
  </div>
</template>
<script>
  import VueCountUp from 'vue-countupjs'
  export default {
    name: 'home',
    components: {
      "v-countup": VueCountUp
    }
  }
</script>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章