当前位置:   article > 正文

30分钟~使用uni-app框架-整合vant、nuxt_uniapp nuxt

uniapp nuxt

uni-app搭建项目

1. 通过 HBuilderX 可视化界面

2. 通过vue-cli命令行

vue create -p dcloudio/uni-preset-vue my-project

uni-app整合vant

前言

vant ui有h5版和微信小程序版。其h5版 (vant)只能用于h5,其微信小程序版(vant weapp)可用于微信和App,从uni-app 2.4.7起,H5和QQ小程序也支持了微信小程序组件

H5版本

通过 npm & yarn 安装 -&link

  1. # 通过 yarn 安装 注意指定版本
  2. yarn add vant
  3. # 通过 npm 安装 2.10.6
  4. # Vue 2 项目,安装 Vant 2
  5. npm i vant@latest-v2

引入 vant 组件(全局引入)
注意:1、是否全局引入,根据项目而定

2、现使用node版本12.6.0,如果使用16.15.0会出现版本兼容问题(引入 vant/lib/index.css 报错)

  1. // 引入vant
  2. // #ifdef H5
  3. import Vant from 'vant';
  4. import {
  5. ConfigProvider
  6. } from "vant";
  7. import 'vant/lib/index.css';
  8. // #endif
  9. // #ifdef H5
  10. app.use(Vant); //
  11. app.use(ConfigProvider);
  12. // #endif

微信小程序版本

使用步骤

下载代码

  • 在项目根目录下新建 wxcomponents 目录 ,此目录应该与 components 目录同级。

  • 直接通过 git 下载 vant-weapp 最新源代码,并将dist目录拷贝到新建的wxcomponents目录下,并重命名distvant-weapp

  • 在 pages.json 的 globalStyle 中 引入所需要的组件

    1. "globalStyle": {
    2. "pageOrientation": "portrait",
    3. "navigationBarTitleText": "Hello uniapp",
    4. "navigationBarTextStyle": "white",
    5. "navigationBarBackgroundColor": "#007AFF",
    6. "backgroundColor": "#F8F8F8",
    7. "backgroundColorTop": "#F4F5F6",
    8. "backgroundColorBottom": "#F4F5F6",
    9. "usingComponents": { //这里为方便,全局引入了所有组件,也可以在某个page下单独引用某个组件
    10. "demo-block": "/wxcomponents/vant/demo-block/index",
    11. "van-action-sheet": "/wxcomponents/vant/action-sheet/index",
    12. "van-area": "/wxcomponents/vant/area/index",
    13. // "van-badge": "/wxcomponents/vant/badge/index",
    14. // "van-badge-group": "/wxcomponents/vant/badge-group/index",
    15. "van-button": "/wxcomponents/vant/button/index",
    16. "van-card": "/wxcomponents/vant/card/index",
    17. "van-cell": "/wxcomponents/vant/cell/index",
    18. "van-cell-group": "/wxcomponents/vant/cell-group/index",
    19. "van-checkbox": "/wxcomponents/vant/checkbox/index",
    20. "van-checkbox-group": "/wxcomponents/vant/checkbox-group/index",
    21. "van-col": "/wxcomponents/vant/col/index",
    22. "van-dialog": "/wxcomponents/vant/dialog/index",
    23. "van-field": "/wxcomponents/vant/field/index",
    24. "van-goods-action": "/wxcomponents/vant/goods-action/index",
    25. "van-goods-action-icon": "/wxcomponents/vant/goods-action-icon/index",
    26. "van-goods-action-button": "/wxcomponents/vant/goods-action-button/index",
    27. "van-icon": "/wxcomponents/vant/icon/index",
    28. "van-loading": "/wxcomponents/vant/loading/index",
    29. "van-nav-bar": "/wxcomponents/vant/nav-bar/index",
    30. "van-notice-bar": "/wxcomponents/vant/notice-bar/index",
    31. "van-notify": "/wxcomponents/vant/notify/index",
    32. "van-panel": "/wxcomponents/vant/panel/index",
    33. "van-popup": "/wxcomponents/vant/popup/index",
    34. "van-progress": "/wxcomponents/vant/progress/index",
    35. "van-radio": "/wxcomponents/vant/radio/index",
    36. "van-radio-group": "/wxcomponents/vant/radio-group/index",
    37. "van-row": "/wxcomponents/vant/row/index",
    38. "van-search": "/wxcomponents/vant/search/index",
    39. "van-slider": "/wxcomponents/vant/slider/index",
    40. "van-stepper": "/wxcomponents/vant/stepper/index",
    41. "van-steps": "/wxcomponents/vant/steps/index",
    42. "van-submit-bar": "/wxcomponents/vant/submit-bar/index",
    43. "van-swipe-cell": "/wxcomponents/vant/swipe-cell/index",
    44. "van-switch": "/wxcomponents/vant/switch/index",
    45. // "van-switch-cell": "/wxcomponents/vant/switch-cell/index",
    46. "van-tab": "/wxcomponents/vant/tab/index",
    47. "van-tabs": "/wxcomponents/vant/tabs/index",
    48. "van-tabbar": "/wxcomponents/vant/tabbar/index",
    49. "van-tabbar-item": "/wxcomponents/vant/tabbar-item/index",
    50. "van-tag": "/wxcomponents/vant/tag/index",
    51. "van-toast": "/wxcomponents/vant/toast/index",
    52. "van-transition": "/wxcomponents/vant/transition/index",
    53. "van-tree-select": "/wxcomponents/vant/tree-select/index",
    54. "van-datetime-picker": "/wxcomponents/vant/datetime-picker/index",
    55. "van-rate": "/wxcomponents/vant/rate/index",
    56. "van-collapse": "/wxcomponents/vant/collapse/index",
    57. "van-collapse-item": "/wxcomponents/vant/collapse-item/index",
    58. "van-picker": "/wxcomponents/vant/picker/index"
    59. },
    60. "mp-360": {
    61. "navigationStyle": "custom"
    62. },
    63. "h5": {
    64. "maxWidth": 1190,
    65. "navigationBarTextStyle": "black",
    66. "navigationBarBackgroundColor": "#F1F1F1"
    67. }
    68. },

uni-app整合nuxt

在使用 uni-app 开发 小程序 与 h5 的时候,难免需要开启 SSR 渲染,这时候我们需要接入基于 vue nuxt 框架

下载 Nuxt 框架 ,无需使用 create-nuxt-app. 脚手架

yarn add nuxt

配置 package.json 文件

  1. {
  2. "name": "my-app",
  3. "scripts": {
  4. "dev": "nuxt",
  5. "build": "nuxt build",
  6. "generate": "nuxt generate",
  7. "start": "nuxt start"
  8. }
  9. }

配置 nuxt.config.js 文件

  1. import {
  2. resolve
  3. } from 'path'
  4. export default {
  5. head: {
  6. title: '~~',
  7. meta: [{
  8. charset: 'utf-8'
  9. },
  10. {
  11. 'http-equiv': 'X-UA-Compatible',
  12. content: 'IE=Edge'
  13. },
  14. {
  15. name: 'viewport',
  16. content: 'width=750, user-scalable=no, target-densitydpi=device-dpi'
  17. },
  18. {
  19. name: "apple-mobile-web-app-capable",
  20. content: "yes"
  21. },
  22. {
  23. name: 'viewport',
  24. content: 'width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover'
  25. },
  26. {
  27. hid: 'description',
  28. name: 'description',
  29. content:'~~'
  30. }
  31. ],
  32. link: [{
  33. rel: 'icon',
  34. type: 'image/x-icon',
  35. href: '/favicon.ico'
  36. }],
  37. },
  38. // 引入公共scss
  39. styleResources: {
  40. scss: ['~/uni.scss']
  41. },
  42. srcDir: 'src/',
  43. }

Nuxt pages下不同的页面对应layout

layouts/default.vue:

  1. <template>
  2. <div>
  3. <div class="title">这里是自定义也页面的头部(布局)</div>
  4. <!-- nuxt可以理解为所对应的.vue页面的内容 -->
  5. <nuxt/>
  6. <div class="footer">这里是自定义页面的底部(布局)</div>
  7. </div>
  8. </template>
  9. <script>
  10. export default {
  11. }
  12. </script>
  13. <style scoped>
  14. .title,.footer{
  15. padding: 20px;
  16. }
  17. .title{
  18. background: pink;
  19. }
  20. .footer{
  21. background: yellow
  22. }
  23. </style>

 运行项目发现会报错误 postcss 错误,需要重新配置一下 postcss.config.js ,需要依赖 nuxt-start、cross-env、css-loader

yarn add nuxt-start cross-env css-loader

注意:下载 css-loader 版本要与项目匹配,建议下载 css-loader@5

配置 postcss.config.js


postcss 文件需要做 nuxtuni-app 兼容处理

  1. const path = require('path')
  2. // nuxt兼容
  3. if (process.env.VUE_APP_IS_NUXT) {
  4. module.exports = {
  5. plugins: {}
  6. }
  7. } else {
  8. // uni-app原有
  9. module.exports = {
  10. parser: require('postcss-comment'),
  11. plugins: [
  12. require('postcss-import')({
  13. resolve(id, basedir, importOptions) {
  14. if (id.startsWith('~@/')) {
  15. return path.resolve(process.env.UNI_INPUT_DIR, id.substr(3))
  16. } else if (id.startsWith('@/')) {
  17. return path.resolve(process.env.UNI_INPUT_DIR, id.substr(2))
  18. } else if (id.startsWith('/') && !id.startsWith('//')) {
  19. return path.resolve(process.env.UNI_INPUT_DIR, id.substr(1))
  20. }
  21. return id
  22. }
  23. }),
  24. require('autoprefixer')({
  25. remove: process.env.UNI_PLATFORM !== 'h5'
  26. }),
  27. require('@dcloudio/vue-cli-plugin-uni/packages/postcss')
  28. ]
  29. }
  30. }

新package.json文件:

  1. {
  2. "name": "my-app",
  3. "scripts": {
  4. "dev": "cross-env VUE_APP_IS_NUXT=true nuxt",
  5. "prd": "cross-env VUE_APP_IS_NUXT=true nuxt build",
  6. "generate": "nuxt generate",
  7. "start": "nuxt start"
  8. }
  9. }

运行 yarn dev 会遇到store报错如下:

nuxt报错:[nuxt] store/index.js should export a method that returns a Vuex instance.

store/index.js代码如下:

  1. // 入口文件
  2. import Vue from 'vue'
  3. import Vuex from 'vuex'
  4. Vue.use(Vuex)
  5. const store = new Vuex.Store({
  6. state: {
  7. authenticated: 'a'
  8. }
  9. })
  10. export default store

只要将上方的 store 写法改一下就好了:(即js应该导出一个返回Vuex实例的方法。)

  1. // 入口文件
  2. import Vue from 'vue'
  3. import Vuex from 'vuex'
  4. Vue.use(Vuex)
  5. const store = () => new Vuex.Store({
  6. state: {
  7. authenticated: 'a'
  8. }
  9. })
  10. export default store

运行 npm run dev ( 基于 nuxt 框架的M站 ) 即可,npm run dev:mp-weixin (运行微信小程序)

移动端布局适配 postcss-px-to-viewport(兼容vant)

  1. 我们先把它安装到项目的开发环境中:
 npm i postcss-px-to-viewport -D
  1. 在项目根目录下添加 postcss.config.js 文件
  2. 添加如下配置:
  1. const path = require('path')
  2. if (process.env.VUE_APP_IS_NUXT) {
  3. module.exports = {
  4. plugins: {
  5. // autoprefixer: {}, // 用来给不同的浏览器自动添加相应前缀,如-webkit-,-moz-等等
  6. "postcss-px-to-viewport": {
  7. unitToConvert: "px", // 要转化的单位
  8. viewportWidth: 375, // UI设计稿的宽度
  9. unitPrecision: 13, // 转换后的精度,即小数点位数
  10. propList: ["*"], // 指定转换的css属性的单位,*代表全部css属性的单位都进行转换
  11. viewportUnit: "vw", // 指定需要转换成的视窗单位,默认vw
  12. fontViewportUnit: "vw", // 指定字体需要转换成的视窗单位,默认vw
  13. selectorBlackList: ["wrap"], // 指定不转换为视窗单位的类名,
  14. minPixelValue: 1, // 默认值1,小于或等于1px则不进行转换
  15. mediaQuery: false, // 是否在媒体查询的css代码中也进行转换,默认false
  16. replace: true, // 是否转换后直接更换属性值
  17. exclude: [/node_modules/], // 设置忽略文件,用正则做目录名匹配
  18. landscape: false, // 是否处理横屏情况
  19. landscapeUnit: 'vw', // 横屏时使用的单位
  20. landscapeWidth: 1134 // 横屏时使用的视口宽度
  21. }
  22. }
  23. }
  24. } else {
  25. module.exports = {
  26. parser: require('postcss-comment'),
  27. plugins: [
  28. require('postcss-import')({
  29. resolve(id, basedir, importOptions) {
  30. if (id.startsWith('~@/')) {
  31. return path.resolve(process.env.UNI_INPUT_DIR, id.substr(3))
  32. } else if (id.startsWith('@/')) {
  33. return path.resolve(process.env.UNI_INPUT_DIR, id.substr(2))
  34. } else if (id.startsWith('/') && !id.startsWith('//')) {
  35. return path.resolve(process.env.UNI_INPUT_DIR, id.substr(1))
  36. }
  37. return id
  38. }
  39. }),
  40. require('autoprefixer')({
  41. remove: process.env.UNI_PLATFORM !== 'h5'
  42. }),
  43. require('@dcloudio/vue-cli-plugin-uni/packages/postcss')
  44. ]
  45. }
  46. }

nuxt 添加 vant-UI

  1. 新建插件文件
  2. 注册插件
  3. 使用 vant 插件

1、新建插件文件

在 plugins 目录添加 vant.js 插件文件,用来引用 Vant 组件:

vant.js

  1. /**
  2. * 引入所有vant组件
  3. */
  4. import Vue from 'vue'
  5. import Vant from 'vant'
  6. import 'vant/lib/index.css'
  7. Vue.use(Vant)

 

2、注册插件

在 nuxt.config.js 文件里注册插件:

nuxt.config.js

plugins: [{src'~plugins/vant', ssrtrue}],

注意: ssr(服务器端运行) 要设置为 true,否则浏览器出现 no match 的警告。

3、使用 Vant 标签

page 文件中直接使用标签:

index.vue

  1. /**
  2. * 引入所有vant组件
  3. */
  4. import Vue from 'vue'
  5. import Vant from 'vant'
  6. import 'vant/lib/index.css'
  7. Vue.use(Vant)

vant/lib/vant-css/index.css in ./plugins/vant.js,默认将它当成模块了,发现运行出错

解决方法:将plugins/vant.js中的import 'vant/lib/vant-css/index.css'删除掉,然后在 nuxt.config.js 中使用全局样式

  1. srcDir: 'src/',
  2. css: ['vant/lib/index.css'],
  3. plugins: [{src: '@/plugins/vant', ssr: true}],

nuxt与uni-app打包小程序分包处理

当我们使用 nuxt 框架开发好M站 h5 页面后,一般 nuxt 框架只有 pages 一个文件夹,由于pages文件夹放入页面太多导致打包小程序会出现压缩包太多,所以我们采取分包测试,但是使用nuxt框架不能改变 pages 原有页面结构,所以使用fs进行 pages 复制分包 pages2 

pages.json

  1. // pages.json
  2. {
  3. "pages": [{
  4. "path": "pages/index/index",
  5. "style": {
  6. "navigationBarTitleText": "uni-app"
  7. }
  8. }],
  9. "subPackages": [{
  10. "root": "pages2",// 分包
  11. "pages": [{
  12. "path": "sub"
  13. }]
  14. }],
  15. "globalStyle": {
  16. "navigationBarTextStyle": "black",
  17. "navigationBarTitleText": "uni-app",
  18. "navigationBarBackgroundColor": "#F8F8F8",
  19. "backgroundColor": "#F8F8F8",
  20. "usingComponents": {}
  21. }
  22. }

buildFileMap.js =>  复制 pages 页面到 pages2
 

  1. const fs = require('fs');
  2. const path = require('path'); //系统路径模块
  3. const process = require('process');
  4. copyFileMove('./src/pages', './src/pages2');
  5. function copyFileMove(src, dist) {
  6. delHandle(dist); // 先删除
  7. fs.mkdir(dist, function() {
  8. // 创建文件夹
  9. copyHandle(src, dist);
  10. });
  11. };
  12. // 复制文件夹文件
  13. function copyHandle(src, dist) {
  14. fs.readdir(src, function(err, paths) {
  15. if (!err && paths) {
  16. paths.forEach((p) => {
  17. let _src = src + '/' + p;
  18. let _dist = dist + '/' + p;
  19. fs.stat(_src, function(err, stat) {
  20. if (stat.isFile()) {
  21. fs.copyFileSync(_src, _dist);
  22. } else if (stat.isDirectory()) {
  23. // 创建文件夹
  24. fs.mkdir(_dist, function() {
  25. copyHandle(_src, _dist);
  26. });
  27. }
  28. })
  29. })
  30. }
  31. })
  32. };
  33. // 删除文件夹
  34. function delHandle(src, callback) {
  35. if (!src) return;
  36. let isExist = fs.existsSync(src);
  37. if (isExist) {
  38. var list = fs.readdirSync(src)
  39. list.forEach(function(v, i) {
  40. let target = src + '/' + v;
  41. if (fs.statSync(target).isFile()) {
  42. fs.unlinkSync(target);
  43. } else if (fs.statSync(target).isDirectory()) {
  44. delHandle(target, callback);
  45. }
  46. });
  47. fs.rmdirSync(src);
  48. }
  49. }

nextFileMap.js => 删除 pages2 文件夹

  1. const fs = require('fs');
  2. // 删除文件
  3. function delDir(src, callback) {
  4. if (!src) return;
  5. let isExist = fs.existsSync(src);
  6. if (isExist) {
  7. var list = fs.readdirSync(src)
  8. list.forEach(function(v, i) {
  9. let target = src + '/' + v;
  10. if (fs.statSync(target).isFile()) {
  11. fs.unlinkSync(target);
  12. } else if (fs.statSync(target).isDirectory()) {
  13. delDir(target, callback);
  14. }
  15. });
  16. fs.rmdirSync(src);
  17. }
  18. }
  19. delDir('./src/pages2', function() {
  20. // console.log('删除成功:', './src/pages3');
  21. });

执行node命令  => npm run build:mp-weixin

  1. "scripts": {
  2. "serve": "npm run dev:h5",
  3. "build": "npm run build:h5",
  4. "build:mp-weixin": "node buildFileMap.js && cross-env NODE_ENV=production UNI_PLATFORM=mp-weixin vue-cli-service uni-build && node nextFileMap.js",
  5. }

uni-app跨平台开发 

跨端兼容

条件编译是用特殊的注释作为标记,在编译的时候根据这些特殊的注释,将注释里的代码编译道不同平台
写法:以 #ifdef 平台名 开头,以 #endif 结尾
平台标识
值 ===> 平台
APP-PLUS ===> 5+App
H5 ===> H5
MP-WEIXIN ===> 微信小程序
MP-ALIPAY ===> 支付宝
MP-BAIDU ===> 百度
MP-TOUTIAO ===> 头条
MP-QQ ===> QQ

代码跨平台兼容

HTML

  1. <!-- #ifdef H5 -->
  2. <view >h5页面显示</view>
  3. <!-- #endif -->
  4. <!-- #ifdef MP-WEIXIN -->
  5. <view >微信小程序页面显示</view>
  6. <!-- #endif -->

JS

  1. // #ifdef APP-PLUS
  2. ...业务代码
  3. // #endif

CSS

  1. /* #ifdef APP-PLUS */
  2. ...style样式代码
  3. /* #endif */

打包编译

  1. {
  2. "name": "my-app",
  3. "scripts": {
  4. "dev:h5": "uni", // H5
  5. "dev:nuxt": "nuxt", // Nuxt
  6. "dev:mp-weixin": "uni -p mp-weixin", // 微信小程序
  7. "build-dev:h5": "uni build", // H5
  8. "build-dev:nuxt": "nuxt build", // Nuxt
  9. "build-dev:mp-weixin": "uni build -p mp-weixin", // 微信小程序
  10. }
  11. }

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读