Vue開發仿京東商場app

vue3-jd-h5

項目介紹

vue3-jd-h5是一個電商H5頁面前端項目,基於Vue 3.0.0 + Vant 3.0.0 實現,主要包括首頁、分類頁面、個人頁面、購物車等,部分效果以下圖。javascript

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








</div>html

本地線下代碼vue2.6在分支demo中,使用mockjs數據進行開發,效果圖請點擊這裏前端

master分支是線上生產環境代碼,由於部分後臺接口已經掛了😫,可能沒法看到實際效果。vue

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>java

項目的初始化

若是你在安裝包的時候速度比較慢,那是由於NPM服務器在國外,這裏給你們推薦一個能夠隨時切換NPM鏡像的工具NRM,有時候,咱們開發的時候,爲了加快安裝包的安裝速度,咱們須要切換鏡像源爲國內的,可是,若是須要發佈一些本身的組件到NPM的時候,又要來回切換回來,有了這個咱們就方便多了!使用$ npm install -g nrm全局安裝,而後,可使用nrm ls 查看全部鏡像:node

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,主要是管理包版本的,若是有興趣的小夥伴,能夠本身去了解一下。react

安裝

進入剛纔clone下來的項目根目錄,安裝相關依賴,體驗 vue3 新特性。ios

npm安裝:git

npm install

yarn安裝:github

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 project
vue 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.x vue3
beforeCreate setup(替代)
created setup(替代)
beforeMount onBeforeMount
mounted onMounted
beforeUpdate onBeforeUpdate
updated onUpdated
beforeDestroy onBeforeUnmount
destroyed onUnmounted
errorCaptured onErrorCaptured

新鉤子

除了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.$attrs
emit: ƒ ()       // 等同 this.$emit()
isServer: false   // 是不是服務端渲染
listeners: Object   // 等同 vue2.x中的this.$listeners
parent: VueComponent  // 等同 vue2.x中的this.$parent
refs: Object  // 等同 vue2.x中的this.$refs
root: Vue  // 這個root是咱們在main.js中,使用newVue()的時候,返回的全局惟一的實例對象,注意別和單文件組建中的this混淆了
slots: {}   // 等同 vue2.x中的this.$slots
ssrContext:{}    // 服務端渲染相關

注意:在 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; // true

state.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) // 2

plusOne.value++ // 錯誤,plusOne是隻讀的!

或者也能夠是個對象,可使用具備getset功能的對象來建立可寫ref對象。

const count = ref(1)
// computed接收一個對象做爲入參
const plusOne = computed({
  get: () => count.value + 1,
  set: val => {
    count.value = val - 1
  }
})

plusOne.value = 1
console.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 ref
const 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

相關文章
相關標籤/搜索