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

一、善用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>

步驟一般有三部,

第一步,引入、

第二步註冊、

第三步纔是正式的使用,

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

我們可以藉助一下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)
})

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

<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

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

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>
  )
}

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

當我們寫組件的時候,通常我們都需要從父組件傳遞一系列的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" 傳入內部組件。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章