目录
- watch方法使用技巧
- echarts图表使用优化
正文
1:watch方法使用技巧---化繁为简的(watch同时代替mounted/created)
场景一:
组件创建的时候我们获取一次列表,同时监听input框,每当发生变化的时候重新获取一次筛选后的列表这个场景,常规做法如下
created(){
this.fetchPostList()
},
watch: {
searchInputValue(){
this.fetchPostList()
}
}
复制代码
下面是优化方法:
声明immediate:true表示创建组件时立马执行一次
watch: {
searchInputValue:{
handler: 'fetchPostList',
immediate: true
}
}
复制代码
场景二:
数组对象的深度watch,对象属性的watch
<div id="app">
<input type="text" v-model:value="childrens.name" />
<input type="text" v-model:value="lastName" />
</div>
<script type="text/javascript">
var vm = new Vue( {
el: '#app',
data: {
childrens: {
name: '小强',
age: 20,
sex: '男'
},
tdArray:["1","2"],
lastName:"张三"
},
watch:{
childrens:{
handler:function(val,oldval){
console.log(val.name)
},
deep:true//对象内部的属性监听,也叫深度监听
},
'childrens.name':function(val,oldval){
console.log(val+"aaa")
},//键路径必须加上引号
lastName:function(val,oldval){
console.log(this.lastName)
},
tdArray(){
console.log('数组更新了')
}
},//以V-model绑定数据时使用的数据变化监测
} );
vm.$watch("lastName",function(val,oldval){
console.log(val)
})//主动调用$watch方法来进行数据监测
</script>
复制代码
2.echarts图表使用优化
echarts在浏览器resize的时候我们希望图表也进行resize,常规做法如下;
mounted(){
this.initEcharts()
},
methods:{
// 画echarts图
initChart(dataSrc){
let option = {
};
let mychart = echarts.init(document.getElementById('networdId'));
mychart.setOption(option);
window.addEventListener('resize', () => { mychart.resize(); });
}
} 复制代码
优化:
import _ from 'lodash' // 导入lodash
computed:{
equTypeAlertChartDom() {
let echartsDom = document.getElementById('equTypeEchartsDom')
return echartsDom && echarts.init(echartsDom) },
/**
* 图表resize节流,这里使用了lodash,也可以自己使用setTimout实现节流
*/
equTypeChartResize() {
return _.throttle(() => {
this.equTypeAlertChartDom && this.equTypeAlertChartDom.resize(), 500)
},
},
mounted(){ window.addEventListener('resize', this.workBenchGplotChartDomResize) this.dataProcess( (chartsData) => { this.initChart(chartsData) }) },
destroyed() { window.removeEventListener('resize', this.workBenchGplotChartDomResize)},methods:{
// 画echarts图 initChart(dataSrc){ let option = { ... 省略配置项 ... }; this.workBenchGplotChartDom.setOption(option); } }
}
复制代码