溫馨提示×

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

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

vue技術(shù)分享之你可能不知道的7個(gè)秘密

發(fā)布時(shí)間:2020-09-13 20:23:35 來源:腳本之家 閱讀:132 作者:Haorooms 欄目:web開發(fā)

前言

本文是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),頁(yè)面跳轉(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)站的支持!

向AI問一下細(xì)節(jié)

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

AI