就在前段時(shí)間,vue官方發(fā)布了3.0.0-beta.1 版本,趁著五一假期有時(shí)間,就把之前的一個(gè)電商商城的項(xiàng)目,用最新的[Composition API](https://vue-composition-api-rfc.netlify.com/)i拿來改造一下!
??GitHub地址請(qǐng)?jiān)L問??:[https://github.com/GitHubGanKai/vue-jd-h5](https://github.com/GitHubGanKai/vue-jd-h5)? ? ? ? ? ? ?
##? 項(xiàng)目介紹
`vue-jd-h5`是一個(gè)電商H5頁面前端項(xiàng)目,基于**Vue 3.0.0-beta.1** +? Vant 實(shí)現(xiàn),主要包括首頁、分類頁面、我的頁面、購物車等。
??本地線下代碼**vue2.6**在分支<a target='_blank' >demo</a>中,使用**mockjs**數(shù)據(jù)進(jìn)行開發(fā),效果圖請(qǐng)點(diǎn)擊??<a target='_blank' >這里</a>
??master分支是線上生產(chǎn)環(huán)境代碼,因?yàn)椴糠趾笈_(tái)接口已經(jīng)掛了??,可能無法看到實(shí)際效果<a target='_blank' >??項(xiàng)目線上地址</a>
?? 本項(xiàng)目還有很多不足之處,如果有想為此做貢獻(xiàn)的伙伴,也歡迎給我們提出PR,或者issue ;
?? 本項(xiàng)目是免費(fèi)開源的,如果有伙伴想要在次基礎(chǔ)上進(jìn)行二次開發(fā),可以clone或者fork整個(gè)倉庫,如果能幫助到您,我將感到非常高興,如果您覺得這個(gè)項(xiàng)目不錯(cuò)還請(qǐng)給個(gè)start!??
## 搭建步驟
1. 首先,選擇一個(gè)文件,將代碼clone到本地:
```bash
git clone https://github.com/GitHubGanKai/vue-jd-h5.git
```
2. 查看所有分支:
```bash
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
```
3. 切換到分支**demo_vue3**開始進(jìn)行開發(fā)!
## 項(xiàng)目的初始化
??如果你在安裝包的時(shí)候速度比較慢,那是因?yàn)镹PM服務(wù)器在國(guó)外,這里給大家推薦一個(gè)可以隨時(shí)切換NPM鏡像的工具??[NRM](https://www.npmjs.com/package/nrm),有時(shí)候,我們開發(fā)的時(shí)候,為了加快安裝包的安裝速度,我們需要切換鏡像源為國(guó)內(nèi)的,但是,如果需要發(fā)布一些自己的組件到NPM的時(shí)候,又要來回切換回來,有了這個(gè)我們就方便多了!使用`$ npm install -g nrm`全局安裝,然后,可以使用`nrm ls` 查看所有鏡像:
```bash
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`? 可以隨時(shí)切換源,當(dāng)然了還有一個(gè)npm包版本管理工具[nvm](https://github.com/nvm-sh/nvm),主要是管理包版本的,如果有興趣的小伙伴,可以自己去了解一下,這里就不啰嗦了??!
### 安裝
進(jìn)入剛才clone下來的項(xiàng)目根目錄,安裝`@vue/composition-api` 體驗(yàn) vue3 新特性。
`npm`安裝:
```javascript
npm install @vue/composition-api --save
```
`yarn`安裝:
```javascript
yarn add @vue/composition-api
```
**CDN**
```html
<script src="https://unpkg.com/@vue/composition-api/dist/vue-composition-api.umd.js"></script>
```
通過全局變量 `window.vueCompositionApi` 來使用。
### 使用
在使用任何 `@vue/composition-api` 提供的能力前,必須先通過 `Vue.use()` 進(jìn)行安裝:
在入口文件`main.js`中:
```javascript
import Vue from 'vue';
import VueCompositionApi from '@vue/composition-api';
Vue.use(VueCompositionApi);
```
安裝插件后,您就可以使用新的 [Composition API](https://vue-composition-api-rfc.netlify.com/) 來開發(fā)組件了。
??目前vue官方為vue-cli提供了一個(gè)插件[vue-cli-plugin-vue-next](https://github.com/vuejs/vue-cli-plugin-vue-next),你也可以直接在項(xiàng)目中直接添加最新的版本!
```bash
# in an existing Vue CLI project
vue add vue-next
```
**如果有想從零開始體驗(yàn)新版本的小伙伴可以采用這種方法進(jìn)行安裝,由于我們這個(gè)項(xiàng)目有依賴第三方庫,如果全局安裝,整個(gè)項(xiàng)目第三方UI庫都無法運(yùn)行!所以我們還是選擇采用安裝`@vue/composition-api`來進(jìn)行體驗(yàn),從而慢慢過渡到vue3最新版本!**
## Vue 3.0 Composition-API基本特性體驗(yàn)
###? setup函數(shù)
`setup()` 函數(shù)是 vue3 中專門為組件提供的新屬性,相當(dāng)于2.x版本中的`created`函數(shù),之前版本的組件邏輯選項(xiàng),現(xiàn)在都統(tǒng)一放在這個(gè)函數(shù)中處理。它為我們使用 vue3 的 `Composition API` 新特性提供了統(tǒng)一的入口,具體可以參考如下:
|? ? ? vue2.x? ? ? |? ? ? vue3? ? ? |
| :--------------: | :-------------: |
| ~~beforeCreate~~ |? setup(替代)? |
|? ~~created~~? ? |? setup(替代)? |
|? beforeMount? ? |? onBeforeMount? |
|? ? mounted? ? ? |? ? onMounted? ? |
|? beforeUpdate? | onBeforeUpdate? |
|? ? updated? ? ? |? ? onUpdated? ? |
|? beforeDestroy? | onBeforeUnmount |
|? ? destroyed? ? |? onUnmounted? |
|? errorCaptured? | onErrorCaptured |
**setup** 函數(shù)會(huì)在相對(duì)于2.x來說,會(huì)在 **beforeCreate** 之后、**created** 之前執(zhí)行!
#### **新鉤子**
除了2.x生命周期等效項(xiàng)之外,Composition API還提供了以下debug hooks:
- `onRenderTracked`
- `onRenderTriggered`
兩個(gè)鉤子都收到`DebuggerEvent`類似于`onTrack`和`onTrigger`觀察者的選項(xiàng):
```javascript
export default {
? onRenderTriggered(e) {
? ? debugger
? ? // inspect which dependency is causing the component to re-render
? }
}
```
### 依賴注入
`provide`和`inject`啟用類似于2.x `provide/inject`選項(xiàng)的依賴項(xiàng)注入。兩者都只能在`setup()`當(dāng)前活動(dòng)實(shí)例期間調(diào)用。
```javascript
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`接受可選的默認(rèn)值作為第二個(gè)參數(shù)。如果未提供默認(rèn)值,并且在Provide上下文中找不到該屬性,則`inject`返回`undefined`。
**注入 響應(yīng)式數(shù)據(jù)**
為了保持提供的值和注入的值之間的響應(yīng)式,可以使用`ref`
```javascript
// 在父組建中
const themeRef = ref('dark')
provide(ThemeSymbol, themeRef)
// 組件中
const theme = inject(ThemeSymbol, ref('light'))
watchEffect(() => {
? console.log(`theme set to: ${theme.value}`)
})
```
#### setup函數(shù)
1. 因?yàn)閌setup`函數(shù)接收2個(gè)形參,第一個(gè)是`initProps`,即父組建傳送過來的值!,第二個(gè)形參是一個(gè)**上下文對(duì)象**?
`setupContext`,這個(gè)對(duì)象的主要屬性有 :
```javascript
attrs: Object? ? ? ? ? // 等同 vue 2.x中的 this.$attrs
emit: ? ()? ? ? ? ? ? ? // 等同 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? ? ? ? ? ? ? // 這個(gè)root是我們?cè)趍ain.js中,使用new Vue()的時(shí)候,返回的全局唯一的實(shí)例對(duì)象,注意別和單文件組建中的this混淆了
slots: {}? ? ? ? ? ? ? // 等同 vue2.x中的this.$slots
ssrContext:{}? ? ? ? ? // 服務(wù)端渲染相關(guān)
```
??**注意**:在 `setup()` 函數(shù)中無法訪問到 `this`的,不管這個(gè)`this`指的是全局的的vue對(duì)象(即:在main.js 中使用new生成的那個(gè)全局的vue實(shí)例對(duì)象),還是指單文件組建的對(duì)象。
但是,如果我們想要訪問當(dāng)前組件的實(shí)例對(duì)象,那該怎么辦呢?我們可以引入`getCurrentInstance`這個(gè)api,返回值就是當(dāng)前組建的實(shí)例!
```javascript
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添加的這個(gè)地方需要結(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自動(dòng)展開(unwrap)
`ref()` 函數(shù)用來根據(jù)給定的值創(chuàng)建一個(gè)**響應(yīng)式**的**數(shù)據(jù)對(duì)象**,`ref()` 函數(shù)調(diào)用的返回值是一個(gè)被包裝后的對(duì)象(RefImpl),這個(gè)對(duì)象上只有一個(gè) `.value` 屬性,如果我們?cè)赻setup`函數(shù)中,想要訪問的對(duì)象的值,可以通過`.value`來獲取,但是如果是在`<template>`**模版中**,直接訪問即可,不需要`.value`!
```javascript
import { ref } from '@vue/composition-api'
setup() {
? ? const active = ref("");
? ? const timeData = ref(36000000);
? ? return {
? ? ? ? active,
? ? ? ? timeData
? ? }
}
```
```html
<template>
? <p>活動(dòng)狀態(tài):{{active}}</p>
? <p>活動(dòng)時(shí)間:{{timeData}}</p>
</template>
```
??注意:不要將`Array`放入`ref`中,數(shù)組索引屬性無法進(jìn)行自動(dòng)展開,也**不要**使用 `Array` 直接存取 `ref` 對(duì)象:
```javascript
const state = reactive({
? list: [ref(0)],
});
// 不會(huì)自動(dòng)展開, 須使用 `.value`
state.list[0].value === 0; // true
state.list.push(ref(1));
// 不會(huì)自動(dòng)展開, 須使用 `.value`
state.list[1].value === 1; // true
```
當(dāng)我們需要操作DOM的時(shí)候,比如我們?cè)陧?xiàng)目中使用`swiper`需要獲取DOM,那么我們還可以這樣??!
```javascript
? <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ù)中定義一個(gè)`const mySwiper = ref(null);`,之前在vue2.x中,我們是通過`this.$refs.mySwiper`來獲取DOM對(duì)象的,現(xiàn)在也可以使用`ref`函數(shù)代替,返回的`mySwiper`要和`template`中綁定的`ref`相同!
```javascript
import { ref, onMounted } from "@vue/composition-api";
setup(props, { attrs, slots, parent, root, emit, refs }) {
? const mySwiper = ref(null);
? onMounted(() => {
? ? // 通過mySwiper.value 即可獲取到DOM對(duì)象!
? ? // 同時(shí)也可以使用vue2.x中的refs.mySwiper ,他其實(shí)mySwiper.value 是同一個(gè)DOM對(duì)象!
? ? mySwiper.value.swiper.slideTo(3, 1000, false);
? });
? return {
? ? mySwiper
? }
}
```
####? reactive
`reactive()` 函數(shù)接收一個(gè)普通對(duì)象,返回一個(gè)響應(yīng)式的數(shù)據(jù)對(duì)象,等價(jià)于 `vue 2.x` 中的 `Vue.observable()` 函數(shù),`vue 3.x` 中提供了 `reactive()` 函數(shù),用來創(chuàng)建響應(yīng)式的數(shù)據(jù)對(duì)象`Observer`,`ref`中我們一般存放的是**基本類型數(shù)據(jù)**,如果是引用類型的我們可以使用`reactive`函數(shù)。
當(dāng)`reactive`函數(shù)中,接收的類型是一個(gè)`Array`數(shù)組的時(shí)候,我們可以在這個(gè)`Array`外面在用對(duì)象包裹一層,然后給對(duì)象添加一個(gè)屬性比如:`value`(這個(gè)屬性名你可以自己隨便叫什么),他的值就是這個(gè)數(shù)組!
```javascript
<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ù)組中每個(gè)對(duì)象都變成響應(yīng)式的對(duì)象
? ? const tabImgs = reactive({
? ? ? value: []
? ? });
? ? const ball = reactive({
? ? ? show: false,
? ? ? el: ""
? ? });
? ? return {
? ? ? active,
? ? ? timeData,
? ? ? tabImgs,
? ? ? ...toRefs(ball),
? ? };
? }
};
</script>
```
那么在`template`模版中我們想要訪問這個(gè)數(shù)組的時(shí)候就是需要使用`.value`的形式來獲取這個(gè)數(shù)組的值。
```html
<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()` 用來判斷某個(gè)值是否為 `ref()` 創(chuàng)建出來的對(duì)象;當(dāng)需要展開某個(gè)可能為 `ref()` 創(chuàng)建出來的值的時(shí)候,可以使用`isRef`來判斷!
```javascript
import { isRef } from '@vue/composition-api'
setup(){
? const headerActive = ref(false);
? // 在setup函數(shù)中,如果是響應(yīng)式的對(duì)象,在訪問屬性的時(shí)候,一定要加上.value來訪問!
? const unwrapped = isRef(headerActive) ? headerActive.value : headerActive
? return {}
}
```
#### toRefs
`toRefs`函數(shù)會(huì)將**響應(yīng)式對(duì)象**轉(zhuǎn)換為**普通對(duì)象**,其中返回的對(duì)象上的每個(gè)屬性都是指向原始對(duì)象中相應(yīng)屬性的`ref`,將一個(gè)對(duì)象上的所有屬性轉(zhuǎn)換成響應(yīng)式的時(shí)候,將會(huì)非常有用!
```javascript
import { reactive,toRefs } from '@vue/composition-api'
setup(){
? // ball 是一個(gè) Observer
? const ball = reactive({
? ? ? show: false,
? ? ? el: ""
? ? });
? // ballToRefs 就是一個(gè)普通的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對(duì)象展開,我們就可以直接在template模板中直接這樣使用這個(gè)對(duì)象上的所有屬性!
? }
}
```
點(diǎn)擊添加按鈕,小球飛入購物車動(dòng)畫:
```html
<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ù)的第一個(gè)參數(shù),可以接收一個(gè)函數(shù),或者是一個(gè)對(duì)象!如果是函數(shù)默認(rèn)是`getter`函數(shù),并為`getter`返回的值返回一個(gè)只讀的`ref`對(duì)象。
```javascript
import { computed } from '@vue/composition-api'
const count = ref(1)
// computed接收一個(gè)函數(shù)作為入?yún)?/p>
const plusOne = computed(() => count.value + 1)
console.log(plusOne.value) // 2
plusOne.value++ // 錯(cuò)誤,plusOne是只讀的!
```
或者也可以是個(gè)函數(shù),可以使用具有`get`和`set`功能的對(duì)象來創(chuàng)建可寫`ref`對(duì)象。
```javascript
const count = ref(1)
// computed接收一個(gè)對(duì)象作為入?yún)?/p>
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?)`
該`watch`API與2.x `this.$watch`(以及相應(yīng)的`watch`選項(xiàng))完全等效。
**觀察單一來源**
觀察者數(shù)據(jù)源可以是返回值的getter函數(shù),也可以直接是ref:
```javascript
// 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多個(gè)來源**
觀察者還可以使用數(shù)組同時(shí)監(jiān)視多個(gè)源:
```javascript
const me = reactive({ age: 24, name: 'gk' })
// reactive類型的
watch(
? [() => me.age, () => me.name], // 監(jiān)聽reactive多個(gè)數(shù)據(jù)源,可以傳入一個(gè)數(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 //默認(rèn) 在 watch 被創(chuàng)建的時(shí)候執(zhí)行回調(diào)函數(shù)中的代碼,如果lazy為true ,怎創(chuàng)建的時(shí)候,不執(zhí)行!
? }
)
setInterval(() => {
? me.age++
? me.name = 'oldMe'
}, 7000000)
// ref類型的
const work = ref('web')
const addres = ref('sz')
watch(
? [work,address],? // 監(jiān)聽多個(gè)ref數(shù)據(jù)源
? ([work, addres], [oldwork, oldaddres]) => {
? //......
? },
? {
? ? lazy: true
? }
)
```
`watch`和組件的生命周期綁定,當(dāng)組件卸載后,watch也將自動(dòng)停止。在其他情況下,它返回停止句柄,可以調(diào)用該句柄以顯式停止觀察程序:
```javascript
// watch 返回一個(gè)函數(shù)句柄,我們可以決定該watch的停止和開始!
const stopWatch = watch(
? [work,address],? // 監(jiān)聽多個(gè)ref數(shù)據(jù)源
? ([work, addres], [oldwork, oldaddres]) => {
? //......
? },
? {
? ? lazy: true
? }
)
// 調(diào)用停止函數(shù),清除對(duì)work和address的監(jiān)視
stopWatch()
```
### 在 watch 中清除無效的異步任務(wù)
```html
<div class="search-con">
? <svg-icon class="search-icon" icon-class="search"></svg-icon>
? <input v-focus placeholder="搜索、關(guān)鍵詞" v-model="searchText" />
</div>
```
```javascript
setup(props, { attrs, slots, parent, root, emit, refs }){
? const CancelToken = root.$http.CancelToken
? const source = CancelToken.source()
? // 定義響應(yīng)式數(shù)據(jù) keywords
? const searchText = ref('')
? // 向后臺(tái)發(fā)送異步請(qǐng)求
? 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請(qǐng)求,并得到取消axios請(qǐng)求的 cancel函數(shù)
? ? const cancel = getSearchResult(searchText)
? ? // 若 watch 監(jiān)聽被重復(fù)執(zhí)行了,則會(huì)先清除上次未完成的異步請(qǐng)求
? ? onCleanup(cancel)
? },
? // watch 剛被創(chuàng)建的時(shí)候不執(zhí)行
? { lazy: true }
)
? return {
? ? searchText
? }
}
```
## 最后
趁著五一假期,有時(shí)間可以熟悉以下vue3的新特性,可以用這個(gè)項(xiàng)目練練手!但是實(shí)際工作中,個(gè)人覺得沒必要從Vue2.x升級(jí)到vue3,以下是個(gè)人分析:
vue3新增 Composition API。新的 API 兼容 Vue2.x,只需要在項(xiàng)目中單獨(dú)引入 @vue/composition-api 這個(gè)包就能夠解決我們目前 Vue2.x 中存在的一些個(gè)別難題比如:如何組織邏輯,以及如何在多個(gè)組件之間抽取和復(fù)用邏輯。基于 Vue 2.x 目前的 API 我們有一些常見的邏輯復(fù)用模式,但都或多或少存在一些問題:
這些模式包括:
1. Mixins
2. 高階組件 (Higher-order Components, aka HOCs)
3. Renderless Components (基于 scoped slots / 作用域插槽封裝邏輯的組件)
總體來說,以上這些模式存在以下問題:
1. 模版中的數(shù)據(jù)來源不清晰。舉例來說,當(dāng)一個(gè)組件中使用了多個(gè) mixin 的時(shí)候,光看模版會(huì)很難分清一個(gè)屬性到底是來自哪一個(gè) mixin。HOC 也有類似的問題。
2. 命名空間沖突。由不同開發(fā)者開發(fā)的 mixin 無法保證不會(huì)正好用到一樣的屬性或是方法名。HOC 在注入的 props 中也存在類似問題。
3. 性能。HOC 和 Renderless Components 都需要額外的組件實(shí)例嵌套來封裝邏輯,導(dǎo)致無謂的性能開銷。
vue3中,新增 `Composition API`。而且新的`API`兼容 `Vue2.x`,只需要在項(xiàng)目中,單獨(dú)引入 `@vue/composition-api` 這個(gè)包就可以,就能夠解決我們目前 以上大部分問題。同時(shí),如果我直接升級(jí)到 `Vue3.x`,我要做的事情會(huì)更多,只要當(dāng)前項(xiàng)目中使用到的第三方ui庫,都需要重新改造,以及升級(jí)后的諸多坑要填!剛開始的時(shí)候,我就是直接在當(dāng)前腳手架的基礎(chǔ)上 `vue add vue-next` 安裝升級(jí),但是只要是有依賴第三方生態(tài)庫的地方,就有許多的坑。。。
`Vue3.x` 沒有導(dǎo)出默認(rèn)對(duì)象 `export default`,在第三方生態(tài)中,常用`Vue.xxx()`來進(jìn)行依賴,現(xiàn)在這些語法需要重寫,工作量可不小啊!
如果是新團(tuán)隊(duì)、小型的項(xiàng)目,可以嘗試使用vue3進(jìn)行嘗試開發(fā),慢慢過度,當(dāng) `Vue3.x` 正式 發(fā)布 后,而且周邊生態(tài)跟上來了,就可以直接用vue3了!
在B站直播的時(shí)候, 尤大也說了,目前vue3beta版本, 最重要的是**提升穩(wěn)定性**,和對(duì)**第三方工具庫的支持**。
--------------
?? 看完三件事:
如果你覺得這篇內(nèi)容對(duì)你挺有啟發(fā),我想邀請(qǐng)你幫我個(gè)小忙:
點(diǎn)贊,讓更多的人也能看到這篇內(nèi)容,也方便自己隨時(shí)找到這篇內(nèi)容(收藏不點(diǎn)贊,都是耍流氓 -_-)
關(guān)注我們,不定期分好文章。
也看看其它文章
??歡迎你把自己的學(xué)習(xí)體會(huì)寫在留言區(qū),與我和其他同學(xué)一起討論。如果你覺得有所收獲,也歡迎把文章分享給你的朋友。