溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

vue3.0.1beta怎么搭建仿京東的電商H5項目

發(fā)布時間:2020-07-28 15:44:04 來源:億速云 閱讀:190 作者:小豬 欄目:web開發(fā)

這篇文章主要講解了vue3.0.1beta怎么搭建仿京東的電商H5項目,內(nèi)容清晰明了,對此有興趣的小伙伴可以學(xué)習(xí)一下,相信大家閱讀完之后會有幫助。

項目介紹

vue-jd-h6是一個電商H5頁面前端項目,基于Vue 3.0.0-beta.1 + Vant 實現(xiàn),主要包括首頁、分類頁面、我的頁面、購物車等。

本地線下代碼vue2.6在分支demo中,使用mockjs數(shù)據(jù)進行開發(fā),效果圖請點擊�這里

master分支是線上生產(chǎn)環(huán)境代碼,因為部分后臺接口已經(jīng)掛了�,不建議使用!

本項目還有很多不足之處,如果有想為此做貢獻的伙伴,也歡迎給我們提出PR,或者issue ;

本項目是免費開源的,如果有伙伴想要在次基礎(chǔ)上進行二次開發(fā),可以clone或者fork整個倉庫,如果能幫助到您,我將感到非常高興,如果您覺得這個項目不錯還請給個start!�

搭建步驟

首先,選擇一個文件,將代碼clone到本地:

git clone https://github.com/GitHubGanKai/vue-jd-h6.git

查看所有分支:

gankaideMacBook-Pro:vue-jd-h6 gankai$ git branch -a
 demo
 demo_vue3
 dev
 feature
 gh-pages
* master
 remotes/origin/HEAD -> origin/master
 remotes/origin/demo
 remotes/origin/demo_vue3
 remotes/origin/dev
 remotes/origin/feature
 remotes/origin/gh-pages
 remotes/origin/master

切換到分支demo_vue3開始進行開發(fā)!

項目的初始化

�如果你在安裝包的時候速度比較慢,那是因為NPM服務(wù)器在國外,這里給大家推薦一個可以隨時切換NPM鏡像的工具�NRM,有時候,我們開發(fā)的時候,為了加快安裝包的安裝速度,我們需要切換鏡像源為國內(nèi)的,但是,如果需要發(fā)布一些自己的組件到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/

如果需要使用淘寶鏡像,執(zhí)行: nrm use taobao 可以隨時切換源,當(dāng)然了還有一個npm包版本管理工具nvm,主要是管理包版本的,如果有興趣的小伙伴,可以自己去了解一下,這里就不啰嗦了�!

安裝

進入剛才clone下來的項目根目錄,安裝@vue/composition-api 體驗 vue3 新特性。

npm安裝:

npm install @vue/composition-api --save

yarn安裝:

yarn add @vue/composition-api

CDN

<script src="https://unpkg.com/@vue/composition-api/dist/vue-composition-api.umd.js"></script>

通過全局變量 window.vueCompositionApi 來使用。

使用

在使用任何 @vue/composition-api 提供的能力前,必須先通過 Vue.use() 進行安裝:

在入口文件main.js中:

import Vue from 'vue';
import VueCompositionApi from '@vue/composition-api';

Vue.use(VueCompositionApi);

安裝插件后,您就可以使用新的Composition API 來開發(fā)組件了。

&#9888;&#65039;目前vue官方為vue-cli提供了一個插件vue-cli-plugin-vue-next,你也可以直接在項目中直接添加最新的版本!

# in an existing Vue CLI project
vue add vue-next

如果有想從零開始體驗新版本的小伙伴可以采用這種方法進行安裝,由于我們這個項目有依賴第三方庫,如果全局安裝,整個項目第三方UI庫都無法運行!所以我們還是選擇采用安裝@vue/composition-api來進行體驗,從而慢慢過渡到vue3最新版本

Vue 3.0 Composition-API基本特性體驗

setup函數(shù)

setup() 函數(shù)是 vue3 中專門為組件提供的新屬性,相當(dāng)于2.x版本中的created函數(shù),之前版本的組件邏輯選項,現(xiàn)在都統(tǒng)一放在這個函數(shù)中處理。它為我們使用 vue3 的 Composition API 新特性提供了統(tǒng)一的入口,具體聲明周期相關(guān)勾子,可以參考如下:

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

ps:感謝評論區(qū)小伙伴提出的疑問:如果你的項目是在vue2.x的基礎(chǔ)上,再安裝Composition API 來開發(fā)的,那么, setup 函數(shù),會在 beforeCreate 之后created 之前執(zhí)行!如果你是直接通過vue add vue-next安裝最新的 vue3.0.x beta,那么setup會在beforeCreate和created之前執(zhí)行!

新鉤子

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

  • onRenderTracked
  • onRenderTriggered

兩個鉤子都收到DebuggerEvent類似于onTrack和onTrigger觀察者的選項:

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

依賴注入

provide和inject啟用類似于2.x provide/inject選項的依賴項注入。兩者都只能在setup()當(dāng)前活動實例期間調(diào)用。

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接受可選的默認值作為第二個參數(shù)。如果未提供默認值,并且在Provide上下文中找不到該屬性,則inject返回undefined。

注入響應(yīng)式數(shù)據(jù)

為了保持提供的值和注入的值之間的響應(yīng)式,可以使用ref

// 在父組建中
const themeRef = ref('dark')
provide(ThemeSymbol, themeRef)

// 組件中
const theme = inject(ThemeSymbol, ref('light'))
watchEffect(() => {
 console.log(`theme set to: ${theme.value}`)
})

因為setup函數(shù)接收2個形參,第一個是initProps,即父組建傳送過來的值!,第二個形參是一個上下文對象

setupContext,這個對象的主要屬性有 :

attrs: Object // 等同 vue 2.x中的 this.$attrs
emit: &#402; () // 等同 this.$emit()
isServer: false // 是否是服務(wù)端渲染
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:{} // 服務(wù)端渲染相關(guān)

&#9888;&#65039;注意:在 setup() 函數(shù)中無法訪問到 this的,不管這個this指的是全局的的vue對象(即:在main.js 中使用new生成的那個全局的vue實例對象),還是指單文件組建的對象。

但是,如果我們想要訪問當(dāng)前組件的實例對象,那該怎么辦呢?我們可以引入getCurrentInstance這個api,返回值就是當(dāng)前組建的實例!

import { computed, getCurrentInstance } from "@vue/composition-api";
export default {
 name: "svg-icon",
 props: {
 iconClass: {
 type: String,
 required: true
 },
 className: {
 type: String
 }
 },
 setup(initProps,setupContext) { 
 // &#9888;&#65039;注意,如果是通過vue add vue-next添加的這個地方需要結(jié)構(gòu)出ctx
 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() 函數(shù)用來根據(jù)給定的值創(chuàng)建一個響應(yīng)式的數(shù)據(jù)對象,ref() 函數(shù)調(diào)用的返回值是一個被包裝后的對象(RefImpl),這個對象上只有一個 .value 屬性,如果我們在setup函數(shù)中,想要訪問的對象的值,可以通過.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>活動狀態(tài):{{active}}</p>
 <p>活動時間:{{timeData}}</p>
</template>

&#9888;&#65039;注意:不要將Array放入ref中,數(shù)組索引屬性無法進行自動展開,也不要使用 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

當(dāng)我們需要操作DOM的時候,比如我們在項目中使用swiper需要獲取DOM,那么我們還可以這樣&#56391;!

 <div class="swiper-cls">
 <swiper :options="swiperOption" ref="mySwiper">
 <swiper-slide v-for="(img ,index) in tabImgs.value" :key="index">
  <img class="slide_img" @click="handleClick(img.linkUrl)" :src="img.imgUrl" />
 </swiper-slide>
 </swiper>
 </div>

然后在setup函數(shù)中定義一個const mySwiper = ref(null);,之前在vue2.x中,我們是通過this.$refs.mySwiper來獲取DOM對象的,現(xiàn)在也可以使用ref函數(shù)代替,返回的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() 函數(shù)接收一個普通對象,返回一個響應(yīng)式的數(shù)據(jù)對象,等價于 vue 2.x 中的 Vue.observable() 函數(shù),vue 3.x 中提供了 reactive() 函數(shù),用來創(chuàng)建響應(yīng)式的數(shù)據(jù)對象Observer,ref中我們一般存放的是基本類型數(shù)據(jù),如果是引用類型的我們可以使用reactive函數(shù)。

當(dāng)reactive函數(shù)中,接收的類型是一個Array數(shù)組的時候,我們可以在這個Array外面在用對象包裹一層,然后給對象添加一個屬性比如:value(這個屬性名你可以自己隨便叫什么),他的值就是這個數(shù)組!

<script>
// 使用相關(guān)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數(shù)組中每個對象都變成響應(yīng)式的對象 
 const tabImgs = reactive({
 value: []
 });
 const ball = reactive({
 show: false,
 el: ""
 });
 return {
 active,
 timeData,
 tabImgs,
 ...toRefs(ball),
 };
 }
};
</script>

那么在template模版中我們想要訪問這個數(shù)組的時候就是需要使用.value的形式來獲取這個數(shù)組的值。

<template>
 <div class="swiper-cls">
 <swiper :options="swiperOption" ref="mySwiper">
 <swiper-slide v-for="(img ,index) in tabImgs.value" :key="index">
  <img class="slide_img" @click="handleClick(img.linkUrl)" :src="img.imgUrl" />
 </swiper-slide>
 </swiper>
 </div>
</template>

isRef

isRef() 用來判斷某個值是否為 ref() 創(chuàng)建出來的對象;當(dāng)需要展開某個可能為 ref() 創(chuàng)建出來的值的時候,可以使用isRef來判斷!

import { isRef } from '@vue/composition-api'

setup(){
 const headerActive = ref(false);
 // 在setup函數(shù)中,如果是響應(yīng)式的對象,在訪問屬性的時候,一定要加上.value來訪問!
 const unwrapped = isRef(headerActive) &#63; headerActive.value : headerActive
 return {}
}

toRefs

toRefs函數(shù)會將響應(yīng)式對象轉(zhuǎn)換為普通對象,其中返回的對象上的每個屬性都是指向原始對象中相應(yīng)屬性的ref,將一個對象上的所有屬性轉(zhuǎn)換成響應(yīng)式的時候,將會非常有用!

import { reactive,toRefs } from '@vue/composition-api'
setup(){
 // ball 是一個 Observer
 const ball = reactive({
 show: false,
 el: ""
 });
 // ballToRefs 就是一個普通的Object,但是ballToRefs里面的所有屬性都是響應(yīng)式的(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函數(shù)的第一個參數(shù),可以接收一個函數(shù),或者是一個對象!如果是函數(shù)默認是getter函數(shù),并為getter返回的值返回一個只讀的ref對象。

import { computed } from '@vue/composition-api'

const count = ref(1)
// computed接收一個函數(shù)作為入?yún)?
const plusOne = computed(() => count.value + 1)

console.log(plusOne.value) // 2

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

或者也可以是個對象,可以使用具有g(shù)et和set功能的對象來創(chuàng)建可寫ref對象。

const count = ref(1)
// computed接收一個對象作為入?yún)?
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&#63;)

該watchAPI與2.x this.$watch(以及相應(yīng)的watch選項)完全等效。

觀察單一來源

觀察者數(shù)據(jù)源可以是返回值的getter函數(shù),也可以直接是ref:

// watching a getter函數(shù)
const state = reactive({ count: 0 })
watch(
 () => state.count, // 返回值的getter函數(shù)
 (count, prevCount,onCleanup) => {
 /* ... */
 }
)

// directly watching a ref
const count = ref(0)
watch(
 count, // 也可以直接是ref
 (count, prevCount,onCleanup) => {
 /* ... */
})

watch多個來源

觀察者還可以使用數(shù)組同時監(jiān)視多個源:

const me = reactive({ age: 24, name: 'gk' })
// reactive類型的
watch(
 [() => me.age, () => me.name], // 監(jiān)聽reactive多個數(shù)據(jù)源,可以傳入一個數(shù)組類型,返回getter函數(shù)
 ([age, name], [oldAge, oldName]) => {
 console.log(age) // 新的 age 值
 console.log(name) // 新的 name 值
 console.log(oldAge) // 舊的 age 值
 console.log(oldName) // 新的 name 值
 },
 // options
 {
 lazy: true //默認 在 watch 被創(chuàng)建的時候執(zhí)行回調(diào)函數(shù)中的代碼,如果lazy為true ,怎創(chuàng)建的時候,不執(zhí)行!
 }
)

setInterval(() => {
 me.age++
 me.name = 'oldMe'
}, 7000000)

// ref類型的
const work = ref('web')
const addres = ref('sz')
watch(
 [work,address], // 監(jiān)聽多個ref數(shù)據(jù)源
 ([work, addres], [oldwork, oldaddres]) => {
 //......
 },
 {
 lazy: true 
 }
)

watch和組件的生命周期綁定,當(dāng)組件卸載后,watch也將自動停止。在其他情況下,它返回停止句柄,可以調(diào)用該句柄以顯式停止觀察程序:

// watch 返回一個函數(shù)句柄,我們可以決定該watch的停止和開始!
const stopWatch = watch(
 [work,address], // 監(jiān)聽多個ref數(shù)據(jù)源
 ([work, addres], [oldwork, oldaddres]) => {
 //......
 },
 {
 lazy: true 
 }
)

// 調(diào)用停止函數(shù),清除對work和address的監(jiān)視
stopWatch()

在 watch 中清除無效的異步任務(wù)

<div class="search-con">
 <svg-icon class="search-icon" icon-class="search"></svg-icon>
 <input v-focus placeholder="搜索、關(guān)鍵詞" v-model="searchText" />
</div>
setup(props, { attrs, slots, parent, root, emit, refs }){
 const CancelToken = root.$http.CancelToken 
 const source = CancelToken.source() 
 // 定義響應(yīng)式數(shù)據(jù) searchText
 const searchText = ref('')

 // 向后臺發(fā)送異步請求
 const getSearchResult = searchText => {
 root.$http.post("http://test.happymmall.com/search",{text:searchText}, {
 cancelToken: source.token
 }).then(res => {
 // .....
 });
 return source.cancel
}

// 定義 watch 監(jiān)聽
watch(
 searchText,
 (searchText, oldSearchText, onCleanup) => {
 // 發(fā)送axios請求,并得到取消axios請求的 cancel函數(shù)
 const cancel = getSearchResult(searchText)

 // 若 watch 監(jiān)聽被重復(fù)執(zhí)行了,則會先清除上次未完成的異步請求
 onCleanup(cancel)
 },
 // watch 剛被創(chuàng)建的時候不執(zhí)行
 { lazy: true }
)

 return {
 searchText
 }
}

最后

vue3新增 Composition API。新的 API 兼容 Vue2.x,只需要在項目中單獨引入 @vue/composition-api 這個包就能夠解決我們目前 Vue2.x中存在的個別難題。比如:如何組織邏輯,以及如何在多個組件之間抽取和復(fù)用邏輯?;?Vue 2.x 目前的 API 我們有一些常見的邏輯復(fù)用模式,但都或多或少存在一些問題:

這些模式包括:

  • Mixins
  • 高階組件 (Higher-order Components, aka HOCs)
  • Renderless Components (基于 scoped slots / 作用域插槽封裝邏輯的組件)

總體來說,以上這些模式存在以下問題:

  1. 模版中的數(shù)據(jù)來源不清晰。舉例來說,當(dāng)一個組件中使用了多個 mixin 的時候,光看模版會很難分清一個屬性到底是來自哪一個 mixin。HOC 也有類似的問題。
  2. 命名空間沖突。由不同開發(fā)者開發(fā)的 mixin 無法保證不會正好用到一樣的屬性或是方法名。HOC 在注入的 props 中也存在類似問題。
  3. 性能。HOC 和 Renderless Components 都需要額外的組件實例嵌套來封裝邏輯,導(dǎo)致無謂的性能開銷。

vue3中,新增 Composition API。而且新的API兼容 Vue2.x,只需要在項目中,單獨引入 @vue/composition-api 這個包就可以,就能夠解決我們目前 以上大部分問題。同時,如果我直接升級到 Vue3.x,我要做的事情會更多,只要當(dāng)前項目中使用到的第三方ui庫,都需要重新改造,以及升級后的諸多坑要填!剛開始的時候,我就是直接在當(dāng)前腳手架的基礎(chǔ)上 vue add vue-next 安裝升級,但是只要是有依賴第三方生態(tài)庫的地方,就有許多的坑。。。

Vue3.x 沒有導(dǎo)出默認對象 export default,在第三方生態(tài)中,常用Vue.xxx()來進行依賴,現(xiàn)在這些語法需要重寫,工作量可不小?。?/p>

看完上述內(nèi)容,是不是對vue3.0.1beta怎么搭建仿京東的電商H5項目有進一步的了解,如果還想學(xué)習(xí)更多內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI