vue技術(shù)分享之你可能不知道的7個(gè)秘密
前言
本文是vue源碼貢獻(xiàn)值Chris Fritz在公共場(chǎng)合的一場(chǎng)分享,覺得分享里面有不少東西值得借鑒,雖然有些內(nèi)容我在工作中也是這么做的,還是把大神的ppt在這里翻譯一下,希望給朋友帶來一些幫助。
一、善用watch的immediate屬性
這一點(diǎn)我在項(xiàng)目中也是這么寫的。例如有請(qǐng)求需要再也沒初始化的時(shí)候就執(zhí)行一次,然后監(jiān)聽他的變化,很多人這么寫:
created(){ this.fetchPostList() }, watch: { searchInputValue(){ this.fetchPostList() } }
上面的這種寫法我們可以完全如下寫:
watch: { searchInputValue:{ handler: 'fetchPostList', immediate: true } }
二、組件注冊(cè),值得借鑒
一般情況下,我們組件如下寫:
import BaseButton from './baseButton' import BaseIcon from './baseIcon' import BaseInput from './baseInput' export default { components: { BaseButton, BaseIcon, BaseInput } } <BaseInput v-model="searchText" @keydown.enter="search" /> <BaseButton @click="search"> <BaseIcon name="search"/></BaseButton>
步驟一般有三部,
第一步,引入、
第二步注冊(cè)、
第三步才是正式的使用,
這也是最常見和通用的寫法。但是這種寫法經(jīng)典歸經(jīng)典,好多組件,要引入多次,注冊(cè)多次,感覺很煩。
我們可以借助一下webpack,使用 require.context()
方法來創(chuàng)建自己的(模塊)上下文,從而實(shí)現(xiàn)自動(dòng)動(dòng)態(tài)require組件。
思路是:在src文件夾下面main.js中,借助webpack動(dòng)態(tài)將需要的基礎(chǔ)組件統(tǒng)統(tǒng)打包進(jìn)來。
代碼如下:
import Vue from 'vue' import upperFirst from 'lodash/upperFirst' import camelCase from 'lodash/camelCase' // Require in a base component context const requireComponent = require.context( ‘./components', false, /base-[\w-]+\.vue$/ ) requireComponent.keys().forEach(fileName => { // Get component config const componentConfig = requireComponent(fileName) // Get PascalCase name of component const componentName = upperFirst( camelCase(fileName.replace(/^\.\//, '').replace(/\.\w+$/, '')) ) // Register component globally Vue.component(componentName, componentConfig.default || componentConfig) })
這樣我們引入組件只需要第三步就可以了:
<BaseInput v-model="searchText" @keydown.enter="search" /> <BaseButton @click="search"> <BaseIcon name="search"/> </BaseButton>
三、精簡(jiǎn)vuex的modules引入
對(duì)于vuex,我們輸出store如下寫:
import auth from './modules/auth' import posts from './modules/posts' import comments from './modules/comments' // ... export default new Vuex.Store({ modules: { auth, posts, comments, // ... } })
要引入好多modules,然后再注冊(cè)到Vuex.Store中~~
精簡(jiǎn)的做法和上面類似,也是運(yùn)用 require.context()讀取文件,代碼如下:
import camelCase from 'lodash/camelCase' const requireModule = require.context('.', false, /\.js$/) const modules = {} requireModule.keys().forEach(fileName => { // Don't register this file as a Vuex module if (fileName === './index.js') return const moduleName = camelCase( fileName.replace(/(\.\/|\.js)/g, '') ) modules[moduleName] = { namespaced: true, ...requireModule(fileName), } }) export default modules
這樣我們只需如下代碼就可以了:
import modules from './modules' export default new Vuex.Store({ modules })
四、路由的延遲加載
這一點(diǎn),關(guān)于vue的引入,我之前在 vue項(xiàng)目重構(gòu)技術(shù)要點(diǎn)和總結(jié) 中也提及過,可以通過require方式或者import()方式動(dòng)態(tài)加載組件。
{ path: '/admin', name: 'admin-dashboard', component:require('@views/admin').default }
或者
{ path: '/admin', name: 'admin-dashboard', component:() => import('@views/admin') }
加載路由。
五、router key組件刷新
下面這個(gè)場(chǎng)景真的是傷透了很多程序員的心...先默認(rèn)大家用的是Vue-router來實(shí)現(xiàn)路由的控制。 假設(shè)我們?cè)趯懸粋€(gè)博客網(wǎng)站,需求是從/post-haorooms/a,跳轉(zhuǎn)到/post-haorooms/b。然后我們驚人的發(fā)現(xiàn),頁面跳轉(zhuǎn)后數(shù)據(jù)竟然沒更新?!原因是vue-router"智能地"發(fā)現(xiàn)這是同一個(gè)組件,然后它就決定要復(fù)用這個(gè)組件,所以你在created函數(shù)里寫的方法壓根就沒執(zhí)行。通常的解決方案是監(jiān)聽$route的變化來初始化數(shù)據(jù),如下:
data() { return { loading: false, error: null, post: null } }, watch: { '$route': { handler: 'resetData', immediate: true } }, methods: { resetData() { this.loading = false this.error = null this.post = null this.getPost(this.$route.params.id) }, getPost(id){ } }
bug是解決了,可每次這么寫也太不優(yōu)雅了吧?秉持著能偷懶則偷懶的原則,我們希望代碼這樣寫:
data() { return { loading: false, error: null, post: null } }, created () { this.getPost(this.$route.params.id) }, methods () { getPost(postId) { // ... } }
解決方案:給router-view添加一個(gè)唯一的key,這樣即使是公用組件,只要url變化了,就一定會(huì)重新創(chuàng)建這個(gè)組件。
<router-view :key="$route.fullpath"></router-view>
注:我個(gè)人的經(jīng)驗(yàn),這個(gè)一般應(yīng)用在子路由里面,這樣才可以不避免大量重繪,假設(shè)app.vue根目錄添加這個(gè)屬性,那么每次點(diǎn)擊改變地址都會(huì)重繪,還是得不償失的!
六、唯一組件根元素
場(chǎng)景如下:
(Emitted value instead of an instance of Error)
Error compiling template:<div></div>
<div></div>- Component template should contain exactly one root element.
If you are using v-if on multiple elements, use v-else-if
to chain them instead.
模板中div只能有一個(gè),不能如上面那么平行2個(gè)div。
例如如下代碼:
<template> <li v-for="route in routes" :key="route.name" > <router-link :to="route"> {{ route.title }} </router-link> </li> </template>
會(huì)報(bào)錯(cuò)!
我們可以用render函數(shù)來渲染
functional: true, render(h, { props }) { return props.routes.map(route => <li key={route.name}> <router-link to={route}> {route.title} </router-link> </li> ) }
七、組件包裝、事件屬性穿透問題
當(dāng)我們寫組件的時(shí)候,通常我們都需要從父組件傳遞一系列的props到子組件,同時(shí)父組件監(jiān)聽子組件emit過來的一系列事件。舉例子:
//父組件 <BaseInput :value="value" label="密碼" placeholder="請(qǐng)?zhí)顚懨艽a" @input="handleInput" @focus="handleFocus> </BaseInput> //子組件 <template> <label> {{ label }} <input :value="value" :placeholder="placeholder" @focus=$emit('focus', $event)" @input="$emit('input', $event.target.value)" > </label> </template>
這樣寫很不精簡(jiǎn),很多屬性和事件都是手動(dòng)定義的,我們可以如下寫:
<input :value="value" v-bind="$attrs" v-on="listeners" > computed: { listeners() { return { ...this.$listeners, input: event => this.$emit('input', event.target.value) } } }
$attrs包含了父作用域中不作為 prop 被識(shí)別 (且獲取) 的特性綁定 (class 和 style 除外)。當(dāng)一個(gè)組件沒有聲明任何 prop 時(shí),這里會(huì)包含所有父作用域的綁定,并且可以通過 v-bind="$attrs"
傳入內(nèi)部組件。
$listeners包含了父作用域中的 (不含 .native 修飾器的) v-on 事件監(jiān)聽器。它可以通過 v-on="$listeners"
傳入內(nèi)部組件。
總結(jié)
以上所述是小編給大家介紹的vue技術(shù)分享之你可能不知道的7個(gè)秘密,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
相關(guān)文章
vue引用外部JS并調(diào)用JS文件中的方法實(shí)例
我們?cè)谧鰒ue項(xiàng)目時(shí),經(jīng)常會(huì)需要引入js,下面這篇文章主要給大家介紹了關(guān)于vue引用外部JS并調(diào)用JS文件中的方法的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-02-02如何刪除vue項(xiàng)目下的node_modules文件夾
這篇文章主要介紹了如何刪除vue項(xiàng)目下的node_modules文件夾,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-09-09vue3中使用VueParticles實(shí)現(xiàn)粒子動(dòng)態(tài)背景效果
為了提高頁面展示效果,特別類似于登錄界面內(nèi)容比較單一的,粒子效果作為背景經(jīng)常使用到,vue工程中利用vue-particles可以很簡(jiǎn)單的實(shí)現(xiàn)頁面的粒子背景效果,本文給大家分享vue粒子動(dòng)態(tài)背景效果實(shí)現(xiàn)代碼,需要的朋友參考下吧2022-05-05vue項(xiàng)目多環(huán)境配置(.env)的實(shí)現(xiàn)
最常見的多環(huán)境配置,就是開發(fā)環(huán)境配置,和生產(chǎn)環(huán)境配置,本文主要介紹了vue項(xiàng)目多環(huán)境配置的實(shí)現(xiàn),感興趣的可以了解一下2021-07-07vue項(xiàng)目百度地圖如何自定義標(biāo)注marker
這篇文章主要介紹了vue項(xiàng)目百度地圖如何自定義標(biāo)注marker問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03vue實(shí)現(xiàn)點(diǎn)擊導(dǎo)航欄滾動(dòng)頁面到指定位置的功能(推薦)
這篇文章主要介紹了vue實(shí)現(xiàn)點(diǎn)擊導(dǎo)航欄滾動(dòng)頁面到指定位置的功能(推薦),步驟一是是通過獲取不同板塊的滾輪高度,步驟二通過編寫執(zhí)行滾動(dòng)操作的函數(shù),結(jié)合實(shí)例代碼給大家介紹的非常詳細(xì),需要的朋友可以參考下2023-11-11Element-ui table中過濾條件變更表格內(nèi)容的方法
下面小編就為大家分享一篇Element-ui table中過濾條件變更表格內(nèi)容的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-03-03webpack 3 + Vue2 使用dotenv配置多環(huán)境的步驟
這篇文章主要介紹了webpack 3 + Vue2 使用dotenv配置多環(huán)境,env文件在配置文件都可以用, vue頁面用的時(shí)候需要在 webpack.base.conf.js 重新配置,需要的朋友可以參考下2023-11-11簡(jiǎn)單談?wù)剉ue的過渡動(dòng)畫(推薦)
下面小編就為大家?guī)硪黄?jiǎn)單談?wù)剉ue的過渡動(dòng)畫(推薦)。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-10-10