Vue-h5环境搭建的学习笔记

376 阅读3分钟

这里主要记录下vue针对h5环境的搭建学习笔记,感谢友哥(尼克陈),更多内容还请购买小册:juejin.cn/book/684473…

1.初始化项目:

直接使用脚手架vue-cli中的vue create 项目名字即可

配置项目选择如下:

2.引入vant Ui

安装:npm install vant -S

安装成功之后,我们再来安装按需引入 Vant 组件的 babel 插件 babel-plugin-import

// mac用户安装不下来的建议加 sudo
npm install babel-plugin-import -D // 注意这个插件是开发环境下使用,装到 devDependencies 下

项目使用的是 babel7,所以我们在根目录下新建 babel 配置文件babel.config.js

// babel.config.js
module.exports = {
  presets: [
    '@vue/cli-plugin-babel/preset'
  ],
  plugins: [
    ['import', {
      libraryName: 'vant',
      libraryDirectory: 'es',
      style: true
    }, 'vant']
  ]
}

紧接着我们可以在代码中直接引入 Vant 组件,我们来尝试一下能否引入成功,首先去 main.js 引入 Vant,代码如下所示:

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import { Button } from 'vant'

Vue.use(Button)

Vue.config.productionTip = false

new Vue({
  router,
  store,
  renderh => h(App)
}).$mount('#app')

然后可以去 views/Home.vue 页面,可在 template 内部直接使用,代码如下:

<template>
  <div class="home">
    <van-button type="primary">默认按钮</van-button>
  </div>
</template>

<script>
export default {
  name'Home'
}
</script>

3.移动端分辨率适配—rem

首先我们在项目中引入 lib-flexible,如下所示:

//命令行 安装
npm install lib-flexible -S


// 然后在main.js 全局引入
...
import 'lib-flexible/flexible'
...

接下来写样式的时候就都要用 rem 做单位,想想还是有点麻烦,有没有什么好办法还是正常写 px 单位,但是编译代码的时候能转化成 rem。 postcss-pxtorem 帮我吗? 解决了这个棘手的问题,下面老规矩,先安装它:

npm install postcss-pxtorem -D

在项目根目录下新建 postcss.config.js 配置文件,配置代码如下:

module.exports = {
  plugins: {
    'autoprefixer': {
      browsers: ['Android >= 4.0''iOS >= 7'] 
    },
    'postcss-pxtorem': {
      rootValue: 37.5, // vant-UI的官方根字体大小是37.5
      propList: ['*']
    }
  }
}

再来将 views/Home.vue 组件换成下面的内容试一试,单位转换好不好用:

  • font-size: 18PX,单位必须得大写PX,防止不被编译成rem
  • width和height的单位都转换成了rem
<template>
  <div class="home">
    <div>你好</div>
  </div>
</template>

<script>
export default {
  name'Home'
}
</script>

<style lang="less" scoped>
  .home {
    div {
      background: greenyellow;
      width75px;
      height75px;
      font-size18PX;
    }
  }
</style>