Vue你可能不知道的7個技巧

1、善用watch的immediate屬性

這一點我在項目中也是這麼寫的。例若有請求須要再也沒初始化的時候就執行一次,而後監聽他的變化,不少人這麼寫:vue

created(){
    this.fetchPostList()
},
watch: {
    searchInputValue(){
        this.fetchPostList()
    }
}
複製代碼

上面的這種寫法咱們能夠徹底以下寫:webpack

watch: {
    searchInputValue:{
        handler: 'fetchPostList',
        immediate: true
    }
}
複製代碼

2、組件註冊,值得借鑑

通常狀況下,咱們組件以下寫:程序員

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>
複製代碼

步驟通常有三部,web

第一步,引入、vue-router

第二步註冊、vuex

第三步纔是正式的使用,bash

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

咱們能夠藉助一下webpack,使用 require.context() 方法來建立本身的(模塊)上下文,從而實現自動動態require組件。函數

思路是:在src文件夾下面main.js中,藉助webpack動態將須要的基礎組件通通打包進來。post

代碼以下:

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>
複製代碼

3、精簡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
})
複製代碼

4、路由的延遲加載

這一點,關於vue的引入,我以前在vue項目重構技術要點和總結中也說起過,能夠經過require方式或者import()方式動態加載組件。

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

或者

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

加載路由。

5、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根目錄添加這個屬性,那麼每次點擊改變地址都會重繪,仍是得不償失的!

6、惟一組件根元素

場景以下:

(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>
 )
}
複製代碼

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

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

相關文章
相關標籤/搜索