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
git clone https://github.com/GitHubGanKai/vue-jd-h5.git
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
npm run dev
,運行項目;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>
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) { 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.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.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新增 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
安裝升級,可是隻要是有依賴第三方生態庫的地方,就有許多的坑。。。