优雅的vue.js
优雅的vue.js代码
https://www.cnblogs.com/zhengrunlin/p/9164951.html
- watch 与 computed 的巧妙结合
如上图,一个简单的列表页面。
你可能会这么做:
created(){
this.fetchData()
},
watch: {
keyword(){
this.fetchData()
}
}
如果参数比较多,比如上图
关键字筛选,
区域筛选,
设备ID筛选,
分页数,
每页几条数据,
可能会是这样:
data(){
return {
keyword:'',
region:'',
deviceId:'',
page:1
}
},
methods:{
fetchData(paramrs={
keyword:this.keyword,
region:this.region,
deviceId:this.deviceId,
page:this.page,
}){
this.$http.get("/list",paramrs).then("do some thing")
}
},
created(){
this.fetchData()
},
watch: {
keyword(data){
this.keyword=data
this.fetchData()
},
region(data){
this.region=data
this.fetchData()
},
deviceId(data){
this.deviceId=data
this.fetchData()
},
page(data){
this.page=data
this.fetchData()
},
requestParams(params){
this.fetchData(params)
}
}
不过这么写,明显有问题,主要是watch了很多参数,而且函数的处理都差不多,可以修改一下,通过methods处理
data(){
return {
keyword:'',
region:'',
deviceId:'',
page:1
}
},
methods:{
paramsChange(paramsName,paramsValue){
this[paramsName]=paramsValue
this.fetchData()
},
fetchData(paramrs={
keyword:this.keyword,
region:this.region,
deviceId:this.deviceId,
page:this.page,
}){
this.$http.get("/list",paramrs).then("do some thing")
}
},
created(){
this.fetchData()
}
当然这么写,需要在模板里面每个参数change的地方绑定事件,并传递参数值,比如分页change时:
<el-pagination
layout="total, prev, pager, next, jumper"
:total="total"
prev-text="上一页"
next-text="下一页"
@current-change="paramsChange('page',$event)"
>
相比上面的各种watch,代码明显少了很多,但是还有一个问题,那就是要在template的很多地方绑定change事件。
最后,当然是使用我们重点推荐的computed + watch了
data(){
return {
keyword:'',
region:'',
deviceId:'',
page:1
}
},
computed:{
requestParams() {
return {
page: this.page,
region: this.region,
id: this.deviceId,
keyword: this.keyword
}
}
},
methods:{
fetchData(paramrs={
keyword:this.keyword,
region:this.region,
deviceId:this.deviceId,
page:this.page,
}){
this.$http.get("/list",paramrs).then("do some thing")
}
},
watch: {
requestParams: {
handler: 'fetchData',
immediate: true
}
},
通过增加一个computed属性,watch这个属性并设置immediate为true,无需再手动绑定事件,相比之上的方法都要简洁。当然,缺点就是对性能稍微有些影响,不过问题不大。
- 使用mixin提取公共部分
很多列表页其实使用的很多属性都是一样的,比如
分页 page
数量 size
搜索关键 字keyword
表格数据 tableData
这些公共的部分其实可以通过mixin来提取出来
/**
- mixin/table.js
*/
export default {
data() {
return {
keyword: '',
requestKeyword: '',
pages: 1,
size: 10,
total: 0,
tableData: []
}
}
}
在要用到的页面
import mixin from '@/mixin/table'
export default {
mixins: [mixin],
data() {
return {
selectRegion: '',
selectDevice: '',
deviceList: [],
}
}
/* 其他代码 */
...
3. 自动注册全局组件
正常情况下,我们需要使用一个我们自己封装的组件时,需要先引入,再注册,最后才能在template模板中使用。
当有多个页面需要用到这些组件时,那么就需要在每个需要的页面重复这些步骤。
为了简化这些步骤,可以考虑把这些组件作为全局组件来使用,这样每个页面需要时,就可以直接使用了。
不过还有一个问题,那就是需要我们手动的全局注册。
/* main.js */
import Component1 from '@/component/compenent1'
import Component2 from '@/component/compenent2'
import Component3 from '@/component/compenent3'
Vue.component('component1', Component1)
Vue.component('component2', Component2)
Vue.component('component3', Component3)
当组件多了以后,手动注册也变得繁琐起来,可以通过require.context()实现自动注册组件。
/**
- main.js
- 读取componetns下的vue文件并自动注册全局组件
*/
const requireComponent = require.context('./components', false, /.vue$/)
requireComponent.keys().forEach(fileName => {
const componentConfig = requireComponent(fileName)
const componentName = fileName.replace(/^\.\//, '').replace(/\.vue/, '')
Vue.component(componentName, componentConfig.default || componentConfig)
})
4. 自动注册vuex模块
之前我们是这么注册vuex模块的
/* module.js */
import alarm from './modules/alarm'
import history from './modules/history'
import factory from './modules/factory'
import contact from './modules/contact'
import company from './modules/company';
import deviceManage from './modules/device-manage'
import deviceModel from './modules/device-model'
import deviceActivation from './modules/device-activation'
import user from './modules/user'
import role from './modules/role'
import setAlarm from './modules/setAlarm'
import factoryMode from "./modules/factoryMode";
import ScreenDeviceWatch from './modules/screen-device-watch'
import ScreenDeviceForecast from './modules/screen-device-forecast'
export default {
alarm,
company,
deviceManage,
deviceModel,
user,
factory,
contact,
deviceActivation,
history,
role,
setAlarm,
factoryMode,
ScreenDeviceWatch,
ScreenDeviceForecast,
}
/* index.js */
import Vue from 'vue'
import Vuex from 'vuex'
import state from './state'
import getters from './getters'
import modules from './modules'
import actions from './actions'
import mutations from './mutations'
Vue.use(Vuex)
export default new Vuex.Store({
state,
getters,
mutations,
actions,
modules
})
可以发现每个模块都要我们手动导入,然后加入到module里面,如此重复。当模块不多还好,假如项目大了,有50个模块,那就得要做很多重复的工作。
跟注册组件一样,我们还是利用require.context来实现。
/**
- 读取./modules下的所有js文件并注册模块
*/
const requireModule = require.context('./modules', false, /.js$/)
const modules = {}
requireModule.keys().forEach(fileName => {
const moduleName = fileName.replace(/(./|.js)/g, '')
modules[moduleName] = {
namespaced: true,
...requireModule(fileName).default
}
})
export default modules
/* index.js */
import Vue from 'vue'
import Vuex from 'vuex'
import modules from './modules'
Vue.use(Vuex)
export default new Vuex.Store({
state,
getters,
mutations,
actions,
modules
})
本文参考自油管上某个国外大神的公开演讲视频,学习了一下觉得很不错,所以在项目中也使用了这些不错的技巧。趁周末有空,写个博客记录一下。
优雅的vue.js的更多相关文章
- 几个你所不知道的技巧助你写出更优雅的vue.js代码
1. watch 与 computed 的巧妙结合 如上图,一个简单的列表页面. 你可能会这么做: created(){ this.fetchData() }, watch: { keyword(){ ...
- Vue.js优雅的实现列表清单的操作
一.Vue.js简要说明 Vue.js (读音 /vjuː/,类似于 view) 是一套构建用户界面的渐进式框架.与前端框架Angular一样, Vue.js在设计上采用MVVM模式,当Vie ...
- Vue.js优雅的实现列表清单
一.Vue.js简要说明 Vue.js (读音 /vjuː/) 是一套构建用户界面的渐进式框架.与前端框架Angular一样, Vue.js在设计上采用MVVM模式,当View视图层发生变化时 ...
- Vue.js 2.0 和 React、Augular等其他框架的全方位对比
引言 这个页面无疑是最难编写的,但也是非常重要的.或许你遇到了一些问题并且先前用其他的框架解决了.来这里的目的是看看Vue是否有更好的解决方案.那么你就来对了. 客观来说,作为核心团队成员,显然我们会 ...
- MVVM大比拼之vue.js源码精析
VUE 源码分析 简介 Vue 是 MVVM 框架中的新贵,如果我没记错的话作者应该毕业不久,现在在google.vue 如作者自己所说,在api设计上受到了很多来自knockout.angularj ...
- vue.js 开发生态总结
---title: Vue 1.0 的技术栈date: 2016-09-26 00:48:50tags:category:--- ## vuejs概述 Vue.js是用于构建交互式的Web界面的库.它 ...
- MVC、MVP、MVVM、Angular.js、Knockout.js、Backbone.js、React.js、Ember.js、Avalon.js、Vue.js 概念摘录
注:文章内容都是摘录性文字,自己阅读的一些笔记,方便日后查看. MVC MVC(Model-View-Controller),M 是指业务模型,V 是指用户界面,C 则是控制器,使用 MVC 的目的是 ...
- 前端开发之走进Vue.js
Vue.js作为目前最热门最具前景的前端框架之一,其提供了一种帮助我们快速构建并开发前端项目的新的思维模式.本文旨在帮助大家认识Vue.js,了解Vue.js的开发流程,并进一步理解如何通过Vue.j ...
- 浅谈Vue.js
作为一名Vue.js的忠实用户,我想有必要写点文章来歌颂这一门美好的语言了,我给它的总体评价是“简单却不失优雅,小巧而不乏大匠”,下面将围绕这句话给大家介绍Vue.js,希望能够激发你对Vue.js的 ...
随机推荐
- bzoj 1050 [HAOI2006]旅行comf (并查集)
题目链接: https://www.lydsy.com/JudgeOnline/problem.php?id=1050 思路: 先将每条边的权值排个序优先小的,然后从小到大枚举每一条边,将其存到并查集 ...
- 【ZJOI2015】诸神眷顾的幻想乡 解题报告
[ZJOI2015]诸神眷顾的幻想乡 Description 幽香是全幻想乡里最受人欢迎的萌妹子,这天,是幽香的2600岁生日,无数幽香的粉丝到了幽香家门前的太阳花田上来为幽香庆祝生日. 粉丝们非常热 ...
- 【bzoj1006】 HNOI2008—神奇的国度
http://www.lydsy.com/JudgeOnline/problem.php?id=1006 (题目链接) 题意 求弦图的最小染色数. Solution 弦图,详情参见论文. 这里我写的加 ...
- (转)Maven学习总结(五)——聚合与继承
孤傲苍狼只为成功找方法,不为失败找借口! Maven学习总结(五)——聚合与继承 一.聚合 如果我们想一次构建多个项目模块,那我们就需要对多个项目模块进行聚合 1.1.聚合配置代码 1 <mod ...
- (转)灵活控制 Hibernate 的日志或 SQL 输出,以便于诊断
背景:项目开发需要.之前对于hibernate日志输出,log4j的绑定,之间的关系一直不是很清楚.终于找到一篇介绍的很详细的文章. 文章出处:https://unmi.cc/hibernate-lo ...
- 数据结构(三)串---KMP模式匹配算法实现及优化
KMP算法实现 #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <stdlib.h> #include ...
- bzoj千题计划254:bzoj2286: [Sdoi2011]消耗战
http://www.lydsy.com/JudgeOnline/problem.php?id=2286 虚树上树形DP #include<cmath> #include<cstdi ...
- 何凯文每日一句打卡||DAY13
- 如何克服presentation恐惧呢?
- Kafka 温故(四):Kafka的安装
Step 1: 下载Kafka > tar -xzf kafka_2.9.2-0.8.1.1.tgz> cd kafka_2.9.2-0.8.1.1 Step 2: 启动服务Kafka用到 ...