vue3-jd-h5

我的项目介绍

vue3-jd-h5是一个电商H5页面前端我的项目,基于Vue 3.0.0 + Vant 3.0.0 实现,次要包含首页、分类页面、我的页面、购物车等,局部成果如下图。

<div style="text-align:center">








</div>

本地线下代码vue2.6在分支demo中,应用mockjs数据进行开发,效果图请点击这里

master分支是线上生产环境代码,因为局部后盾接口曾经挂了????,可能无奈看到实际效果。

vue3搭建步骤

  1. 首先,在本地抉择一个文件,将代码clone到本地:
git clone https://github.com/GitHubGanKai/vue-jd-h5.git 
  1. 查看所有分支:
gankaideMacBook-Pro:vue-jd-h5 gankai$ git branch -a  demo  vue-next  dev  feature  gh-pages* master  remotes/origin/HEAD -> origin/master  remotes/origin/demo  remotes/origin/vue-next  remotes/origin/dev  remotes/origin/feature  remotes/origin/gh-pages  remotes/origin/master
  1. 切换到分支vue-next开始进行开发!
  2. 在 IDEA 命令行中运行命令:npm install,下载相干依赖;
  3. 开发环境 在 IDEA 命令行中运行命令:npm run dev,运行我的项目;
  4. 在 IDEA 命令行中运行命令:npm run dll:build,打包我的项目,而后手机扫描上面二维码体验利用的成果。

<div style="text-align:center">

</div>

我的项目的初始化

如果你在安装包的时候速度比较慢,那是因为NPM服务器在国外,这里给大家举荐一个能够随时切换NPM镜像的工具NRM,有时候,咱们开发的时候,为了放慢安装包的装置速度,咱们须要切换镜像源为国内的,然而,如果须要公布一些本人的组件到NPM的时候,又要来回切换回来,有了这个咱们就不便多了!应用$ npm install -g nrm全局装置,而后,能够应用nrm ls 查看所有镜像:

gankaideMacBook-Pro:~ gankai$ nrm ls  npm -------- https://registry.npmjs.org/* yarn ------- https://registry.yarnpkg.com/  cnpm ------- http://r.cnpmjs.org/  taobao ----- https://registry.npm.taobao.org/  nj --------- https://registry.nodejitsu.com/  npmMirror -- https://skimdb.npmjs.com/registry/  edunpm ----- http://registry.enpmjs.org/

如果须要应用淘宝镜像,执行: nrm use taobao 能够随时切换源,当然了还有一个npm包版本管理工具nvm,次要是治理包版本的,如果有趣味的小伙伴,能够本人去理解一下。

装置

进入方才clone下来的我的项目根目录,装置相干依赖,体验 vue3 新个性。

npm装置:

npm install 

yarn装置:

yarn 

CDN

<script src="https://unpkg.com/vue@next"></script>

应用

在入口文件main.js中:

import Vue from 'vue';import VueCompositionApi from '@vue/composition-api';Vue.use(VueCompositionApi);

装置插件后,您就能够应用新的 Composition API 来开发组件了。

目前vue官网为vue-cli提供了一个插件vue-cli-plugin-vue-next,你也能够间接在我的项目中间接增加最新的版本!

# in an existing Vue CLI projectvue add vue-next

<blockquote style='background-color: #ffffcc;border-left: 4px solid #ffeb3b;padding:10px 20px 10px 20px;box-shadow: 0 2px 4px 0 rgba(0,0,0,0.16),0 2px 10px 0 rgba(0,0,0,0.12)!important;'>

如果有想从零开始体验新版本的小伙伴能够采纳这种办法进行装置,因为咱们这个我的项目有依赖第三方库,如果全局装置,整个我的项目第三方UI库都无奈运行!所以咱们还是抉择采纳装置@vue/composition-api来进行体验,从而缓缓过渡到vue3最新版本

</blockquote>

Vue 3.0 Composition-API根本个性体验

setup函数

setup() 函数是 vue3 中专门为组件提供的新属性,相当于2.x版本中的created函数,之前版本的组件逻辑选项,当初都对立放在这个函数中解决。它为咱们应用 vue3 的 Composition API 新个性提供了对立的入口,setup 函数会在绝对于2.x来说,会在 beforeCreate 之后、created 之前执行!具体能够参考如下:

vue2.xvue3
beforeCreatesetup(代替)
createdsetup(代替)
beforeMountonBeforeMount
mountedonMounted
beforeUpdateonBeforeUpdate
updatedonUpdated
beforeDestroyonBeforeUnmount
destroyedonUnmounted
errorCapturedonErrorCaptured

新钩子

除了2.x生命周期等效项之外,Composition API还提供了以下debug hooks:

  • onRenderTracked
  • onRenderTriggered

两个钩子都收到DebuggerEvent相似于onTrackonTrigger观察者的选项:

export default {  onRenderTriggered(e) {    debugger    // inspect which dependency is causing the component to re-render  }}

依赖注入

provideinject启用相似于2.x provide/inject选项的依赖项注入。两者都只能在setup()以后流动实例期间调用。

import { provide, inject } from '@vue/composition-api'const ThemeSymbol = Symbol()const Ancestor = {  setup() {    provide(ThemeSymbol, 'dark')  }}const Descendent = {  setup() {    const theme = inject(ThemeSymbol, 'light' /* optional default value */)    return {      theme    }  }}

inject承受可选的默认值作为第二个参数。如果未提供默认值,并且在Provide上下文中找不到该属性,则inject返回undefined

注入响应式数据

为了放弃提供的值和注入的值之间的响应式,能够应用ref

// 在父组建中const themeRef = ref('dark')provide(ThemeSymbol, themeRef)// 组件中const theme = inject(ThemeSymbol, ref('light'))watchEffect(() => {  console.log(`theme set to: ${theme.value}`)})
  1. 因为setup函数接管2个形参,第一个是initProps,即父组建传送过去的值!,第二个形参是一个上下文对象

setupContext,这个对象的次要属性有 :

attrs: Object    // 等同 vue 2.x中的 this.$attrsemit: ƒ ()       // 等同 this.$emit()isServer: false   // 是否是服务端渲染listeners: Object   // 等同 vue2.x中的this.$listenersparent: VueComponent  // 等同 vue2.x中的this.$parentrefs: Object  // 等同 vue2.x中的this.$refsroot: Vue  // 这个root是咱们在main.js中,应用newVue()的时候,返回的全局惟一的实例对象,留神别和单文件组建中的this混同了slots: {}   // 等同 vue2.x中的this.$slotsssrContext:{}    // 服务端渲染相干

留神:在 setup() 函数中无法访问到 this的,不论这个this指的是全局的的vue对象(即:在main.js 中应用new生成的那个全局的vue实例对象),还是指单文件组建的对象。

然而,如果咱们想要拜访以后组件的实例对象,那该怎么办呢?咱们能够引入getCurrentInstance这个api,返回值就是以后组建的实例!

import { computed, getCurrentInstance } from "@vue/composition-api";export default {  name: "svg-icon",  props: {    iconClass: {      type: String,      required: true    },    className: {      type: String    }  },  setup(initProps,setupContext) {       const { ctx } = getCurrentInstance();    const iconName = computed(() => {      return `#icon-${initProps.iconClass}`;    });    const svgClass = computed(() => {      if (initProps.className) {        return "svg-icon " + initProps.className;      } else {        return "svg-icon";      }    });    return {      iconName,      svgClass    };  }};</script>

Ref主动开展(unwrap)

ref() 函数用来依据给定的值创立一个响应式数据对象ref() 函数调用的返回值是一个被包装后的对象(RefImpl),这个对象上只有一个 .value 属性,如果咱们在setup函数中,想要拜访的对象的值,能够通过.value来获取,然而如果是在<template>模版中,间接拜访即可,不须要.value

import { ref } from '@vue/composition-api'setup() {    const active = ref("");    const timeData = ref(36000000);    console.log('输入===>',timeData.value)    return {       active,       timeData    }}
<template>  <p>活动状态:{{active}}</p>  <p>流动工夫:{{timeData}}</p></template>

⚠️留神:不要将Array放入ref中,数组索引属性无奈进行主动开展,也不要应用 Array 直接存取 ref 对象:

const state = reactive({  list: [ref(0)],});// 不会主动开展, 须应用 `.value`state.list[0].value === 0; // truestate.list.push(ref(1));// 不会主动开展, 须应用 `.value`state.list[1].value === 1; // true

当咱们须要操作DOM的时候,比方咱们在我的项目中应用swiper须要获取DOM,那么咱们还能够这样????!

  <div class="swiper-cls">      <swiper :options="swiperOption" ref="mySwiper">        <swiper-slide v-for="(img ,index) in tabImgs.value" :key="index">          ![](img.imgUrl)        </swiper-slide>      </swiper>   </div>

而后在setup函数中定义一个const mySwiper = ref(null);,之前在vue2.x中,咱们是通过this.$refs.mySwiper来获取DOM对象的,当初也能够应用ref函数代替,返回的mySwiper要和template中绑定的ref雷同!

import { ref, onMounted } from "@vue/composition-api";setup(props, { attrs, slots, parent, root, emit, refs }) {    const mySwiper = ref(null);  onMounted(() => {    // 通过mySwiper.value 即可获取到DOM对象!    // 同时也能够应用vue2.x中的refs.mySwiper ,他其实mySwiper.value 是同一个DOM对象!    mySwiper.value.swiper.slideTo(3, 1000, false);  });  return {    mySwiper  }}

reactive

reactive() 函数接管一个一般对象,返回一个响应式的数据对象,等价于 vue 2.x 中的 Vue.observable() 函数,vue 3.x 中提供了 reactive() 函数,用来创立响应式的数据对象Observerref中咱们个别寄存的是根本类型数据,如果是援用类型的咱们能够应用reactive函数。

reactive函数中,接管的类型是一个Array数组的时候,咱们能够在这个Array里面在用对象包裹一层,而后给对象增加一个属性比方:value(这个属性名你能够本人轻易叫什么),他的值就是这个数组!

<script>// 应用相干aip之前必须先引入import { ref, reactive } from "@vue/composition-api";export default {  name: "home",  setup(props, { attrs, slots, parent, root, emit, refs }) {        const active = ref("");    const timeData = ref(36000000);    // 将tabImgs数组中每个对象都变成响应式的对象     const tabImgs = reactive({      value: []    });    const ball = reactive({      show: false,      el: ""    });    return {      active,      timeData,      tabImgs,      ...toRefs(ball),    };  }};</script>

那么在template模版中咱们想要拜访这个数组的时候就是须要应用.value的模式来获取这个数组的值。

<template>    <div class="swiper-cls">      <swiper :options="swiperOption" ref="mySwiper">        <swiper-slide v-for="(img ,index) in tabImgs.value" :key="index">          ![](img.imgUrl)        </swiper-slide>      </swiper>    </div></template>

isRef

isRef() 用来判断某个值是否为 ref() 创立进去的对象;当须要开展某个可能为 ref() 创立进去的值的时候,能够应用isRef来判断!

import { isRef } from '@vue/composition-api'setup(){  const headerActive = ref(false);  // 在setup函数中,如果是响应式的对象,在拜访属性的时候,肯定要加上.value来拜访!  const unwrapped = isRef(headerActive) ? headerActive.value : headerActive  return {}}

toRefs

toRefs函数会将响应式对象转换为一般对象,其中返回的对象上的每个属性都是指向原始对象中相应属性的ref,将一个对象上的所有属性转换成响应式的时候,将会十分有用!

import { reactive,toRefs } from '@vue/composition-api'setup(){  // ball 是一个 Observer  const ball = reactive({    show: false,    el: ""  });  // ballToRefs 就是一个一般的Object,然而ballToRefs外面的所有属性都是响应式的(RefImpl)  const ballToRefs  = toRefs(ball)  // ref和原始属性是“链接的”  ball.show = true  console.log(ballToRefs.show) // true  ballToRefs.show.value = false  console.log(ballToRefs.show) // false  return {    ...ballToRefs    // 将ballToRefs对象开展,咱们就能够间接在template模板中间接这样应用这个对象上的所有属性!  }}

点击增加按钮,小球飞入购物车动画:

<template>    <div class="ballWrap">      <transition @before-enter="beforeEnter" @enter="enter" @afterEnter="afterEnter">        <!-- 能够间接应用show-->        <div class="ball" v-if="show">          <li class="inner">            <span class="cubeic-add" @click="addToCart($event,item)">              <svg-icon class="add-icon" icon-class="add"></svg-icon>            </span>          </li>        </div>      </transition>   </div></template>

computed

computed函数的第一个参数,能够接管一个函数,或者是一个对象!如果是函数默认是getter函数,并为getter返回的值返回一个只读的ref对象。

import { computed } from '@vue/composition-api'const count = ref(1)// computed接管一个函数作为入参const plusOne = computed(() => count.value + 1)console.log(plusOne.value) // 2plusOne.value++ // 谬误,plusOne是只读的!

或者也能够是个对象,能够应用具备getset性能的对象来创立可写ref对象。

const count = ref(1)// computed接管一个对象作为入参const plusOne = computed({  get: () => count.value + 1,  set: val => {    count.value = val - 1  }})plusOne.value = 1console.log(count.value) // 0

watch

watch(source, cb, options?)

watchAPI与2.x this.$watch(以及相应的watch选项)齐全等效。

察看繁多起源

观察者数据源能够是返回值的getter函数,也能够间接是ref:

// watching a getter函数const state = reactive({ count: 0 })watch(  () => state.count, // 返回值的getter函数  (count, prevCount,onCleanup) => {    /* ... */  })// directly watching a refconst count = ref(0)watch(  count, // 也能够间接是ref  (count, prevCount,onCleanup) => {  /* ... */})

watch多个起源

观察者还能够应用数组同时监督多个源:

const me = reactive({ age: 24, name: 'gk' })// reactive类型的watch(  [() => me.age, () => me.name], // 监听reactive多个数据源,能够传入一个数组类型,返回getter函数  ([age, name], [oldAge, oldName]) => {    console.log(age) // 新的 age 值    console.log(name) // 新的 name 值    console.log(oldAge) // 旧的 age 值    console.log(oldName) // 新的 name 值  },  // options  {    lazy: true //默认 在 watch 被创立的时候执行回调函数中的代码,如果lazy为true ,怎创立的时候,不执行!  })setInterval(() => {  me.age++  me.name = 'oldMe'}, 7000000)// ref类型的const work = ref('web')const addres = ref('sz')watch(  [work,address],  // 监听多个ref数据源  ([work, addres], [oldwork, oldaddres]) => {   //......  },  {    lazy: true   })

watch和组件的生命周期绑定,当组件卸载后,watch也将主动进行。在其余状况下,它返回进行句柄,能够调用该句柄以显式进行察看程序:

// watch 返回一个函数句柄,咱们能够决定该watch的进行和开始!const stopWatch = watch(  [work,address],  // 监听多个ref数据源  ([work, addres], [oldwork, oldaddres]) => {   //......  },  {    lazy: true   })// 调用进行函数,革除对work和address的监督stopWatch()

在 watch 中革除有效的异步工作

<div class="search-con">  <svg-icon class="search-icon" icon-class="search"></svg-icon>  <input v-focus placeholder="搜寻、关键词" v-model="searchText" /></div>
setup(props, { attrs, slots, parent, root, emit, refs }){  const CancelToken = root.$http.CancelToken   const source = CancelToken.source()   // 定义响应式数据 searchText  const searchText = ref('')  // 向后盾发送异步申请  const getSearchResult = searchText => {   root.$http.post("http://test.happymmall.com/search",{text:searchText}, {     cancelToken: source.token   }).then(res => {    // .....   });  return source.cancel}// 定义 watch 监听watch(  searchText,  (searchText, oldSearchText, onCleanup) => {    // 发送axios申请,并失去勾销axios申请的 cancel函数    const cancel = getSearchResult(searchText)    // 若 watch 监听被反复执行了,则会先革除上次未实现的异步申请    onCleanup(cancel)  },  // watch 刚被创立的时候不执行  { lazy: true })  return {    searchText  }}

最初

vue3新增 Composition API。新的 API 兼容 Vue2.x,只须要在我的项目中独自引入 @vue/composition-api 这个包就可能解决咱们目前 Vue2.x中存在的个别难题。比方:如何组织逻辑,以及如何在多个组件之间抽取和复用逻辑。基于 Vue 2.x 目前的 API 咱们有一些常见的逻辑复用模式,但都或多或少存在一些问题:

这些模式包含:

  1. Mixins
  2. 高阶组件 (Higher-order Components, aka HOCs)
  3. Renderless Components (基于 scoped slots / 作用域插槽封装逻辑的组件)

总体来说,以上这些模式存在以下问题:

  1. 模版中的数据起源不清晰。举例来说,当一个组件中应用了多个 mixin 的时候,光看模版会很难分清一个属性到底是来自哪一个 mixin。HOC 也有相似的问题。
  2. 命名空间抵触。由不同开发者开发的 mixin 无奈保障不会正好用到一样的属性或是办法名。HOC 在注入的 props 中也存在相似问题。
  3. 性能。HOC 和 Renderless Components 都须要额定的组件实例嵌套来封装逻辑,导致无谓的性能开销。

vue3中,新增 Composition API。而且新的API兼容 Vue2.x,只须要在我的项目中,独自引入 @vue/composition-api 这个包就能够,就可能解决咱们目前 以上大部分问题。同时,如果我间接降级到 Vue3.x,我要做的事件会更多,只有以后我的项目中应用到的第三方ui库,都须要从新革新,以及降级后的诸多坑要填!刚开始的时候,我就是间接在以后脚手架的根底上 vue add vue-next 装置降级,然而只有是有依赖第三方生态库的中央,就有许多的坑。。。

我的项目源码:https://github.com/GitHubGanKai/vue3-jd-h5