vue实战项目:项目技巧总结(一)

2020/5/3 11:25:27

本文主要是介绍vue实战项目:项目技巧总结(一),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

一、创建项目及配置

1.1 vue cli2 创建项目

vue init webpack project
复制代码
npm install
复制代码
npm run dev
复制代码

1.2 vue cli3 创建项目

 vue create project
复制代码

选择配置,看个人项目需求

TypeScript 支持使用 TypeScript 书写源码
 Progressive Web App (PWA) Support PWA 支持。
 Router 支持 vue-router 。
 Vuex 支持 vuex 。
 CSS Pre-processors 支持 CSS 预处理器。
 Linter / Formatter 支持代码风格检查和格式化。
 Unit Testing 支持单元测试。
 E2E Testing 支持 E2E 测试。
复制代码

进入到项目根目录

 cd  project
复制代码

启动项目

 npm run serve
复制代码

二、安装 element-UI

npm i element-ui -S
复制代码

2.1main.js 引入

2.1.1 全局引入
import Element from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css';
Vue.use(Element)
复制代码
2.1.2 按需引入

首先,安装 babel-plugin-component

npm install babel-plugin-component -D
复制代码

然后,将 .babelrc 修改为:

{
 "presets": [
  ["es2015", {
   "modules": false
  }]
 ],
 "plugins": [
  [
   "component",
   {
    "libraryName": "element-ui",
    "styleLibraryName": "theme-chalk"
   }
  ]
 ]
}
复制代码

接下来,如果你只希望引入部分组件,比如 ButtonSelect,那么需要在 main.js 中写入以下内容:

import Vue from 'vue';
import { Button, Select } from 'element-ui';
import App from './App.vue';

Vue.component(Button.name, Button);
Vue.component(Select.name, Select);

复制代码

或写为

- Vue.use(Button)
- Vue.use(Select)
复制代码

三、安装 vuex

npm i vuex -s
复制代码
3.1 /src/store 下面的 index.js 中
import Vue from 'vue'
import Vuex from 'vuex'

//挂载 Vuex
Vue.use(Vuex)

//创建 VueX 对象
const store = new Vuex.Store({
state:{name: 'helloVueX',
},
mutations:{},
actions:{},
modules:{}
})

export default store

复制代码
3.2 main.js 引入

store 挂载到当前项目的 Vue 实例当中去

import Vue from 'vue'
import App from './App'
import router from './router'
import store from './store'

Vue.config.productionTip = false

new Vue({
el: '#app',
router,
store, //store:store 和 router 一样,将我们创建的 Vuex 实例挂载到这个 vue 实例中
render: h => h(App)
})
复制代码
3.3 在组件中使用 Vuex
<template>
    <div id='app'>
      name:
      <h1>{{ $store.state.name }}</h1>
    </div>
</template>

methods:{
  add(){
      console.log(this.\$store.state.name)
    }
},
复制代码

更具体的学习文档参考我的网站: 学习文档

四、配置scss环境

4.1.首先安装依赖
npm install node-sass sass-loader --save-dev 
复制代码
4.2.找到 build 中 webpack.base.conf.js,在 rules 中添加 scss 规则
{
  test: /\.scss\$/,
  loaders: ['style', 'css', 'sass']
} 
复制代码
4.3.在 vue 文件中使用
<style lang='scss'>
  
</style>
复制代码

4.4 在 vue 项目全局中引入 scss

1.全局引用时需要安装 sass-resources-loader
npm install sass-resources-loader --save-dev 
复制代码
2.修改 build 中的 utils.js

scss: generateLoaders('sass')

修改为
scss: generateLoaders('sass').concat({
 loader: 'sass-resources-loader',
 options: {
  //你自己的 scss 全局文件的路径
  resources: path.resolve(\_\ _dirname, '../src/style/common.scss')
 }
})
复制代码

如果上面的不能正常编译

//配置 sass 编译路径

function generateSassResourceLoader() {
 let loaders = [
  cssLoader,
  'sass-loader',
  {
   loader: 'sass-resources-loader',
   options: {
    // 多个文件时用数组的形式传入,单个文件时可以直接使用 path.resolve(__dirname, '../static/style/common.scss'
    resources: path.resolve(__dirname, '../src/style/common.scss')
   }
  }
 ];
 if (options.extract) {
  return ExtractTextPlugin.extract({
   use: loaders,
   fallback: 'vue-style-loader'
  });
 } else {
  return ['vue-style-loader'].concat(loaders);
 }
}
复制代码
在 cssLoaders 里面引入
sass:generateSassResourceLoader(),//新加的
scss:generateSassResourceLoader(),//新加的
复制代码

4.5 引入全局的 sass

npm install --s node-sass sass-loader
复制代码

1.首先你需要

npm install --s sass-resources-loader 
复制代码

2.在 build 目录下找到 utils.js 文件

Module build failed: TypeError: this.getResolve is not a function at Object.loader 
复制代码

安装 node-sass 运行报错 vue 安装 node-sass 编译报错 安装node-scss报错 安装 node-scss 报错

在搭建 vue 脚手架 或者是在 vue 项目中,想使用 sass 的功能,

npm install node-sass --save-dev //安装 node-sass
npm install sass-loader --save-dev //安装 sass-loader
npm install style-loader --save-dev //安装 style-loader
复制代码

这是因为当前 sass 的版本太高,webpack 编译时出现了错误,这个时候只需要换成低版本的就行,下面说一下修改方法,很简单,如下,找到 package.json 文件,里面的 "sass-loader"的版本更换掉 就行了。

将 "sass-loader": "^8.0.0",更换成了 "sass-loader": "^7.3.1",
复制代码

也可以先卸载当前版本,然后安装指定的版本

卸载当前版本
npm uninstall sass-loader
复制代码
安装
npm install sass-loader@7.3.1 --save-dev
复制代码

五、配置less环境

安装 lessless-loader
npm install less less-loader --save
复制代码

修改 webpack.base.config.js 文件,配置 loader 加载依赖,让其支持外部的 less,在原来的代码上添加

// 此种方法在控制台中标签样式显示的是style标签样式
{
 test: /\.less$/,
 loader: "style-loader!css-loader!less-loader",
}
复制代码
// 可以在控制台中看到当前标签样式来自于哪个less文件
{
 test: /\.less$/,
 loader: "style-loader!css-loader!less-loader",
 options: {
  sourceMap: true
 }
}
复制代码

在 vue 文件中的 style 标签中添加 lang="less"即可在标签中使用 less,或者外部引入 less

参考文档

六、引入font-awesome

npm install font-awesome --save
复制代码

然后在 main.js 引入 font-awesome/css/font-awesome.min.css 即可。

7、vue 配置网站的 ico

7.1方式一:
<link rel="shortcut icon" href="./favicon.ico" type="image/x-icon" />
复制代码
7.2 方式二
webpack.dev.conf.js
new HtmlWebpackPlugin({
  filename: 'index.html',
  template: 'index.html',
  favicon: 'favicon.ico', // 新增
  inject: true
 }),

 webpack.prod.conf.js
new HtmlWebpackPlugin({
 filename: config.build.index,
 template: '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',
 favicon: 'favicon.ico' // 新增
}),
复制代码

八、引入自定义公共样式

router/index.js 里面引入公共样式

import 'bootstrap/dist/css/bootstrap.css' //引入 bootstrap
import 'bootstrap-vue/dist/bootstrap-vue.css'
import '@/common/common.css'
import '@/common/index.css'
复制代码

九、路由按需加载

const port = () => import('@/pages/port') //入口页面、
复制代码
const router = new Router({
  // mode: 'history',
  routes: [
    {
      path: '/',
      name: 'port',
      component: resolve => require.ensure([], () => resolve(require('@/pages/port')), 'port'),
    }]
})
复制代码

参考文档

十、全局自定义方法

main.js 里面挂载方法到 vue.prototype
Vue.prototype.isMobile = function() {
 let flag = navigator.userAgent.match(
  /(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i
 )
 return flag;
}
复制代码
组件里面使用
mounted: function() {
  this.isMobile();
}
复制代码

十一、引入接口文件暴露到全局

11.1 在 main.js 里面引入接口暴露到全局'
// 接口暴露在全局
import { server } from './config/api'
Vue.prototype.\$server = server;
复制代码
//api.js

export const server = {
getContentMenu: (paramObj)=>fetch('/content/menu',paramObj),//内容详情查询
getContentListPort: (paramObj)=>fetch('/content/list/'+paramObj),//入口页面接口
getContentList:(paramObj)=>fetch('/content/list/'+paramObj),//内容详情查询
getPageviews:(paramObj)=>fetch('/webpage/1/view',paramObj)//流量统计接口
}

组件里面使用:
```js
methods: {
 getPageviews() {
  var that = this;
  let params = {
   pageId: that.pageId,
   pageUrl: that.pageUrl,
  };
  that.\$server.getPageviews(params).then(response => {})
 }
}
复制代码
11.2 axios 方法封装,整个 api.js
import axios from 'axios';

axios.defaults.timeout = 5000;
axios.defaults.baseURL =''; //填写域名

//http request 拦截器
axios.interceptors.request.use(
  config => {
    config.data = JSON.stringify(config.data);
    config.headers = {
      'Content-Type':'application/x-www-form-urlencoded'
    }
    return config;
  },
  error => {
    return Promise.reject(err);
  }
);

//响应拦截器即异常处理
axios.interceptors.response.use(response => {
    return response
}, err => {
    if (err && err.response) {
      switch (err.response.status) {
        case 400:
            console.log('错误请求')
          break;
        case 401:
            console.log('未授权,请重新登录')
          break;
        case 403:
          console.log('拒绝访问')
          break;
        case 404:
          console.log('请求错误,未找到该资源')
          break;
        case 405:
          console.log('请求方法未允许')
          break;
        case 408:
          console.log('请求超时')
          break;
        case 500:
          console.log('服务器端出错')
          break;
        case 501:
          console.log('网络未实现')
          break;
        case 502:
          console.log('网络错误')
          break;
        case 503:
          console.log('服务不可用')
          break;
        case 504:
          console.log('网络超时')
          break;
        case 505:
          console.log('http版本不支持该请求')
          break;
        default:
          console.log(`连接错误${err.response.status}`)
      }
    } else {
      console.log('连接到服务器失败')
    }
    return Promise.resolve(err.response)
})


/**
 * 封装get方法
 * @param url
 * @param data
 * @returns {Promise}
 */

export function fetch(url,params={}){
  return new Promise((resolve,reject) => {
    axios.get(url,{
      params:params
    })
    .then(response => {
      resolve(response.data);
    })
    .catch(err => {
      reject(err)
    })
  })
}


/**
 * 封装post请求
 * @param url
 * @param data
 * @returns {Promise}
 */

 export function post(url,data = {}){
   return new Promise((resolve,reject) => {
     axios.post(url,data)
          .then(response => {
            resolve(response.data);
          },err => {
            reject(err)
          })
   })
 }

/**
 * 官网接口请求封装
 * @param url
 * @param data
 * @returns {Promise}
 */

export const server = {
    getContentMenu: (paramObj)=>fetch('/content/menu',paramObj),//内容详情查询
    getContentListPort: (paramObj)=>fetch('/content/list/'+paramObj),//入口页面接口
    getContentList:(paramObj)=>fetch('/content/list/'+paramObj),//内容详情查询
    getPageviews:(paramObj)=>fetch('/webpage/1/view',paramObj)//流量统计接口
}

复制代码

十二、provide /inject 完美解决不跳转不闪动页面刷新

原理:此方法使用的是 v-if 来控制 router-view 的显示或隐藏,v-if 从 false 变为 true 时,vue 会重新渲染 router-view 区域,所以当参数变化时,只需让 v-if 从 true => false => true,就能实现页面刷新。

12.1 找到route-view
//App.vue

   <template>
      <div id="app">
        <router-view v-if="isRouterAlive"/>
      </div>
   </template>

   <script>
    export default {
      name: 'App',
      provide() {
        return {
          reload: this.reload//调用reload方法
        }
      },
      data() {
        return {
          isRouterAlive: true//一开始router-view为true
        }
      },
    
      methods: {
        reload() {
          this.isRouterAlive = false
             //在修改数据之后使用 $nextTick,则可以在回调中获取更新后的 DOM
          this.$nextTick(() => {
            this.isRouterAlive = true
          })
        }
      }
    }
   </script>
复制代码
12.2在页面操作
    export default {
      name: 'newproduct',
      inject:['reload'],//在export default下面加上这一段
      method:{
        //调用App.vue下的this.reload()方法,来改变v-if的状态
        clickDiv(){//刷新按钮调用的方法
          this.reload()
        }
      }
复制代码

参考文档:如何实现 vue 中不跳转不闪动页面刷新?provide /inject 完美解决方案

放在一篇提示负载太大,所以只两次发了。

vue实战项目:项目技巧总结(二)



这篇关于vue实战项目:项目技巧总结(一)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程