整理Vue 開發技巧
- 1、頁面需要導入多個組件
// 常用寫法
import oneCom from '@/components/home/oneCom'
import twoCom from '@/components/home/twoCom'
components:{
oneCom,
twoCom
}
// 使用 require.context 加載某文件夾下的所有.vue 組件
/**
require.context(directory,useSubdirectories,regExp) >
directory:說明需要檢索的目錄
useSubdirectories:是否檢索子目錄
regExp: 匹配文件的正則表達式,一般是文件名
*/
const path = require('path')
const files = require.context('@/components/home', false, /\.vue$/)
const modules = {}
files.keys().forEach(key => {
const name = path.basename(key, '.vue')
modules[name] = files(key).default || files(key)
})
components:modules
- 2、img 加載失敗
// 有些時候後臺返回圖片地址不一定能打開,所以這個時候應該加一張默認圖片
<img :src="imgUrl" @error="handleError" alt="">
<script>
export default{
data(){
return{
imgUrl:''
}
},
methods:{
handleError(e){
e.target.src=reqiure('圖片路徑')
}
}
}
</script>
3、Vue監聽生命週期函數
export default {
mounted() {
this.chart = echarts.init(this.$el)
// 請求數據,賦值數據 等等一系列操作...
// 監聽窗口發生變化,resize組件
window.addEventListener('resize', this.$_handleResizeChart)
// 通過hook監聽組件銷燬鉤子函數,並取消監聽事件
this.$once('hook:beforeDestroy', () => {
window.removeEventListener('resize', this.$_handleResizeChart)
})
},
updated() {},
created() {},
methods: {
$_handleResizeChart() {
// this.chart.resize()
}
}
}
4、外部監聽生命週期函數
<template>
<!--通過@hook:updated監聽組件的updated生命鉤子函數-->
<!--組件的所有生命週期鉤子都可以通過@hook:鉤子函數名 來監聽觸發-->
<custom-select @hook:updated="$_handleSelectUpdated" />
</template>
<script>
import CustomSelect from '../components/custom-select'
export default {
components: {
CustomSelect
},
methods: {
$_handleSelectUpdated() {
console.log('custom-select組件的updated鉤子函數被觸發')
}
}
}
</script>