PROUMB_ios安卓 testlight proumb.cow/apps/android开发包安装ggzy.jianxi
require.context()
场景:如页面需要导入多个组件,原始写法:
import titleCom from '@/components/home/titleCom'
import bannerCom from '@/components/home/bannerCom'
import cellCom from '@/components/home/cellCom'
components:{titleCom,bannerCom,cellCom}
复制代码
这样就写了大量重复的代码,利用 require.context 可以写成
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
复制代码
这样不管页面引入多少组件,都可以使用这个方法
3.API 方法
实际上是 webpack 的方法,vue 工程一般基于 webpack,所以可以使用
require.context(directory,useSubdirectories,regExp)
接收三个参数:
directory:说明需要检索的目录
useSubdirectories:是否检索子目录
regExp: 匹配文件的正则表达式,一般是文件名
复制代码
2.watch
2.1 常用用法
1.场景:表格初始进来需要调查询接口 getList(),然后input 改变会重新查询
created(){
this.getList()
},
watch: {
inpVal(){
this.getList()
}
}
复制代码
2.2 立即执行
2.可以直接利用 watch 的immediate和handler属性简写
watch: {
inpVal:{
handler: 'getList',
immediate: true
}
}
复制代码
2.3 深度监听
3.watch 的 deep 属性,深度监听,也就是监听复杂数据类型
watch:{
inpValObj:{
handler(newVal,oldVal){
console.log(newVal)
console.log(oldVal)
},
deep:true
}
}
本文介绍了如何使用`require.context`在Vue中批量导入组件,以减少重复代码,并讲解了`watch`对象的常用用法,包括立即执行、深度监听等功能,帮助优化组件管理和响应式更新。
8309

被折叠的 条评论
为什么被折叠?



