1. 程式人生 > >vue技術分享之你可能不知道的7個祕密

vue技術分享之你可能不知道的7個祕密

本文是vue原始碼貢獻值Chris Fritz在公共場合的一場分享,覺得分享裡面有不少東西值得借鑑,雖然有些內容我在工作中也是這麼做的,還是把大神的ppt在這裡翻譯一下,希望給朋友帶來一些幫助。

一、善用watch的immediate屬性

這一點我在專案中也是這麼寫的。例如有請求需要再也沒初始化的時候就執行一次,然後監聽他的變化,很多人這麼寫:

created(){
  this.fetchPostList()
},
watch: {
  searchInputValue(){
    this.fetchPostList()
  }
}

上面的這種寫法我們可以完全如下寫:

watch: {
  searchInputValue:{
    handler: 'fetchPostList',
    immediate: true
  }
}

二、元件註冊,值得借鑑

一般情況下,我們元件如下寫:

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>
//前端全棧學習交流圈:866109386
//面向1-3經驗年前端開發人員
//幫助突破技術瓶頸,提升思維能力

步驟一般有三部,

第一步,引入、

第二步註冊、

第三步才是正式的使用,

這也是最常見和通用的寫法。但是這種寫法經典歸經典,好多元件,要引入多次,註冊多次,感覺很煩。

我們可以藉助一下webpack,使用 require.context() 方法來建立自己的(模組)上下文,從而實現自動動態require元件。

思路是:在src資料夾下面main.js中,藉助webpack動態將需要的基礎元件統統打包進來。

程式碼如下:

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)
})
//前端全棧學習交流圈:866109386
//面向1-3經驗年前端開發人員
//幫助突破技術瓶頸,提升思維能力

這樣我們引入元件只需要第三步就可以了:

<BaseInput
 v-model="searchText"
 @keydown.enter="search"
/>
<BaseButton @click="search">
 <BaseIcon name="search"/>
</BaseButton>

三、精簡vuex的modules引入

對於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,然後再註冊到Vuex.Store中~~

精簡的做法和上面類似,也是運用 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
//前端全棧學習交流圈:866109386
//面向1-3經驗年前端開發人員
//幫助突破技術瓶頸,提升思維能力

這樣我們只需如下程式碼就可以了:

import modules from './modules'
export default new Vuex.Store({
 modules
})

四、路由的延遲載入

這一點,關於vue的引入,我之前在 vue專案重構技術要點和總結 中也提及過,可以通過require方式或者import()方式動態載入元件。

{
 path: '/admin',
 name: 'admin-dashboard',
 component:require('@views/admin').default
}

或者

{
 path: '/admin',
 name: 'admin-dashboard',
 component:() => import('@views/admin')
}

載入路由。

五、router key元件重新整理

下面這個場景真的是傷透了很多程式設計師的心...先預設大家用的是Vue-router來實現路由的控制。 假設我們在寫一個部落格網站,需求是從/post-haorooms/a,跳轉到/post-haorooms/b。然後我們驚人的發現,頁面跳轉後資料竟然沒更新?!原因是vue-router"智慧地"發現這是同一個元件,然後它就決定要複用這個元件,所以你在created函式裡寫的方法壓根就沒執行。通常的解決方案是監聽$route的變化來初始化資料,如下:

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是解決了,可每次這麼寫也太不優雅了吧?秉持著能偷懶則偷懶的原則,我們希望程式碼這樣寫:

data() {
 return {
  loading: false,
  error: null,
  post: null
 }
},
created () {
 this.getPost(this.$route.params.id)
},
methods () {
 getPost(postId) {
  // ...
 }
}

解決方案:給router-view新增一個唯一的key,這樣即使是公用元件,只要url變化了,就一定會重新建立這個元件。

<router-view :key="$route.fullpath"></router-view>

注:個人經驗,這個一般應用在子路由裡面,這樣才可以不避免大量重繪,假設app.vue根目錄新增這個屬性,那麼每次點選改變地址都會重繪,還是得不償失的!

六、唯一元件根元素

場景如下:

(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只能有一個,不能如上面那麼平行2個div。

例如如下程式碼:

<template>
 <li
  v-for="route in routes"
  :key="route.name"
 >
  <router-link :to="route">
   {{ route.title }}
  </router-link>
 </li>
</template>

會報錯!

我們可以用render函式來渲染

functional: true,
render(h, { props }) {
 return props.routes.map(route =>
  <li key={route.name}>
   <router-link to={route}>
    {route.title}
   </router-link>
  </li>
 )
}
//前端全棧學習交流圈:866109386
//面向1-3經驗年前端開發人員
//幫助突破技術瓶頸,提升思維能力

七、元件包裝、事件屬性穿透問題

當我們寫元件的時候,通常我們都需要從父元件傳遞一系列的props到子元件,同時父元件監聽子元件emit過來的一系列事件。舉例子:

//父元件
<BaseInput 
  :value="value"
  label="密碼"
  placeholder="請填寫密碼"
  @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>

這樣寫很不精簡,很多屬性和事件都是手動定義的,我們可以如下寫:

<input
  :value="value"
  v-bind="$attrs"
  v-on="listeners"
>
 
computed: {
 listeners() {
  return {
   ...this.$listeners,
   input: event => 
    this.$emit('input', event.target.value)
  }
 }
}

$attrs包含了父作用域中不作為 prop 被識別 (且獲取) 的特性繫結 (class 和 style 除外)。當一個元件沒有宣告任何 prop 時,這裡會包含所有父作用域的繫結,並且可以通過 v-bind="$attrs" 傳入內部元件。

$listeners包含了父作用域中的 (不含 .native 修飾器的) v-on 事件監聽器。它可以通過 v-on="$listeners" 傳入內部元件。