就在前段時間,vue官方發佈了3.0.0-beta.1 版本,趁着五一假期有時間,就把以前的一個電商商城的項目,用最新的Composition API拿來改造一下!javascript
👉GitHub地址請訪問🔗:github.com/GitHubGanKa…html
vue-jd-h5
是一個電商H5頁面前端項目,基於Vue 3.0.0-beta.1 + Vant 實現,主要包括首頁、分類頁面、個人頁面、購物車等。前端
📖本地線下代碼vue2.6在分支demo中,使用mockjs數據進行開發,效果圖請點擊🔗這裏vue
❌️master分支是線上生產環境代碼,由於部分後臺接口已經掛了😫,不建議使用!java
📌 本項目還有不少不足之處,若是有想爲此作貢獻的夥伴,也歡迎給咱們提出PR,或者issue ;node
🔑 本項目是免費開源的,若是有夥伴想要在次基礎上進行二次開發,能夠clone或者fork整個倉庫,若是能幫助到您,我將感到很是高興,若是您以爲這個項目不錯還請給個start!🙏react
git clone https://github.com/GitHubGanKai/vue-jd-h5.git
複製代碼
gankaideMacBook-Pro:vue-jd-h5 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
複製代碼
💡若是你在安裝包的時候速度比較慢,那是由於NPM服務器在國外,這裏給你們推薦一個能夠隨時切換NPM鏡像的工具👉NRM,有時候,咱們開發的時候,爲了加快安裝包的安裝速度,咱們須要切換鏡像源爲國內的,可是,若是須要發佈一些本身的組件到NPM的時候,又要來回切換回來,有了這個咱們就方便多了!使用$ npm install -g nrm
全局安裝,而後,可使用nrm ls
查看全部鏡像:ios
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,主要是管理包版本的,若是有興趣的小夥伴,能夠本身去了解一下,這裏就不囉嗦了😊!git
進入剛纔clone下來的項目根目錄,安裝@vue/composition-api
體驗 vue3 新特性。github
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 來開發組件了。
⚠️目前vue官方爲vue-cli提供了一個插件vue-cli-plugin-vue-next,你也能夠直接在項目中直接添加最新的版本!
# in an existing Vue CLI project
vue add vue-next
複製代碼
若是有想從零開始體驗新版本的小夥伴能夠採用這種方法進行安裝,因爲咱們這個項目有依賴第三方庫,若是全局安裝,整個項目第三方UI庫都沒法運行!因此咱們仍是選擇採用安裝
@vue/composition-api
來進行體驗,從而慢慢過渡到vue3最新版本
setup()
函數是 vue3 中專門爲組件提供的新屬性,至關於2.x版本中的created
函數,以前版本的組件邏輯選項,如今都統一放在這個函數中處理。它爲咱們使用 vue3 的 Composition API
新特性提供了統一的入口,setup 函數會在相對於2.x來講,會在 beforeCreate 以後、created 以前執行!具體能夠參考以下:
vue2.x | vue3 |
---|---|
setup(替代) | |
setup(替代) | |
beforeMount | onBeforeMount |
mounted | onMounted |
beforeUpdate | onBeforeUpdate |
updated | onUpdated |
beforeDestroy | onBeforeUnmount |
destroyed | onUnmounted |
errorCaptured | onErrorCaptured |
除了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()
當前活動實例期間調用。
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}`)
})
複製代碼
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) {
// ⚠️注意,若是是經過vue add vue-next添加的這個地方須要結構出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()
函數用來根據給定的值建立一個響應式的數據對象,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 class="slide_img" @click="handleClick(img.linkUrl)" :src="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()
函數接收一個普通對象,返回一個響應式的數據對象,等價於 vue 2.x
中的 Vue.observable()
函數,vue 3.x
中提供了 reactive()
函數,用來建立響應式的數據對象Observer
,ref
中咱們通常存放的是基本類型數據,若是是引用類型的咱們可使用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 class="slide_img" @click="handleClick(img.linkUrl)" :src="img.imgUrl" />
</swiper-slide>
</swiper>
</div>
</template>
複製代碼
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
函數會將響應式對象轉換爲普通對象,其中返回的對象上的每一個屬性都是指向原始對象中相應屬性的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
函數的第一個參數,能夠接收一個函數,或者是一個對象!若是是函數默認是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是隻讀的!
複製代碼
或者也能夠是個函數,可使用具備get
和set
功能的對象來建立可寫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(source, cb, options?)
該watch
API與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) => {
/* ... */
})
複製代碼
觀察者還可使用數組同時監視多個源:
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()
複製代碼
<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的新特性,能夠用這個項目練練手!,目前這個項目並無徹底升級成vue3.x,有興趣的小夥伴能夠本身fork過去,將其餘頁面也升級到vue3,當官方正式發佈版本以後,能夠輕鬆上手!
vue3新增 Composition API。新的 API 兼容 Vue2.x,只須要在項目中單獨引入 @vue/composition-api 這個包就可以解決咱們目前 Vue2.x中存在的個別難題。好比:如何組織邏輯,以及如何在多個組件之間抽取和複用邏輯。基於 Vue 2.x 目前的 API 咱們有一些常見的邏輯複用模式,但都或多或少存在一些問題:
這些模式包括:
整體來講,以上這些模式存在如下問題:
vue3中,新增 Composition API
。並且新的API
兼容 Vue2.x
,只須要在項目中,單獨引入 @vue/composition-api
這個包就能夠,就可以解決咱們目前 以上大部分問題。同時,若是我直接升級到 Vue3.x
,我要作的事情會更多,只要當前項目中使用到的第三方ui庫,都須要從新改造,以及升級後的諸多坑要填!剛開始的時候,我就是直接在當前腳手架的基礎上 vue add vue-next
安裝升級,可是隻要是有依賴第三方生態庫的地方,就有許多的坑。。。
Vue3.x
沒有導出默認對象 export default
,在第三方生態中,經常使用Vue.xxx()
來進行依賴,如今這些語法須要重寫,工做量可不小啊!
若是是新團隊、小型的項目,能夠嘗試使用vue3進行嘗試開發,慢慢過分,當 Vue3.x
正式 發佈 後,並且周邊生態跟上來了,就能夠直接用vue3了!
在B站直播的時候, 尤大也說了,目前vue3beta版本, 最重要的是提高穩定性,和對第三方工具庫的支持。
❤️ 看完三件事: 若是你以爲這篇內容對你挺有啓發,我想邀請你幫我個小忙:
點贊,讓更多的人也能看到這篇內容,也方便本身隨時找到這篇內容(收藏不點贊,都是耍流氓 -_-) 關注咱們,不按期分好文章。 也看看其它文章
🔥歡迎你把本身的學習體會寫在留言區,與我和其餘同窗一塊兒討論。若是你以爲有所收穫,也歡迎把文章分享給你的朋友。
本項目在手機端體驗效果更佳,能夠掃描如下二維碼進行體驗!👇