前言
最近在工作中接到了一个任务,切换项目主题色时,修改地图的背景色styleid
,所想了以下两个思路:
- 项目使用的vuetify框架,挂载在vue实例下,如何在map组件中监听到
this.$vuetify.theme.dark
,本想在map组件中使用以下代码计算:
computed: {
styleId() {
console.log('this.$vuetify.theme.dark', this)
if (this.$vuetify.theme.isDark) {
return DARK_MAP_STYLE_ID
}
return LIGHT_MAP_STYLE_ID
},
},
// 结果:this.$vuetify.theme.dark改变时,控制台没有输出this,证明styleId计算属性没有生效
- 找到
this.$vuetify.theme.dark
改变逻辑的地方,然后改变map组件中的styleId
,但是很明显不可行,map实例不会放在vue实例下,map组件复用性强,每个pages都有可能存在map实例
使用方法
通过查找资料发现,watch和compute可以结合使用
如此一来,在computed中styleId
改变的同时,watch中的styleId函数会被执行,map组件中的地图色会跟项目主题色一起改变
computed: {
styleId() {
console.log('this.$vuetify.theme.dark', this)
if (this.$vuetify.theme.isDark) {
return DARK_MAP_STYLE_ID
}
return LIGHT_MAP_STYLE_ID
},
},
watch: {
styleId(val) {
this.map.setMapStyleV2({
styleId: val,
})
},
}
computed和watch的使用
在工作中,总是免不了涉及到computed和watch的使用,但是也容易忘记一些知识,比如是深度监听和在什么场景下使用computed和watch
使用场景
- watch:监听事件,当a的改变,影响b、c、d等多个属性值时使用
- computed:计算事件,当b、c、d等属性值的改变影响a的值时使用
watch的使用
日常使用
watch:{
str(newVal,oldVal){
console.log(newVal,oldVal)
}
}
不日常使用
// 监听复杂类型,比如数组、对象
watch:{
arr:{
handler:(newVal,oldVal)=>{
console.log(newVal,oldVal)
},
deep:true, // 深度监听
immediate:true // 初始化时也被监听到
}
}
// 监听对象中的具体字段
watch: {
'assetsDetails.location': function (newVal) {
if (!newVal) return
this.getLocaltion({ lat: newVal.split(',')[1], lng: newVal.split(',')[0] }).then(e => {
console.log(e)
this.address = e || ''
})
},
},
computed的使用
vue官网是这样子介绍的:
{ [key: string]: Function | { get: Function, set: Function } }
计算属性将被混入到 Vue 实例中。所有 getter 和 setter 的 this 上下文自动地绑定为 Vue 实例。
注意如果你为一个计算属性使用了箭头函数,则 this
不会指向这个组件的实例,不过你仍然可以将其实例作为函数的第一个参数来访问。
computed: {
aDouble: vm => vm.a * 2
}
计算属性的结果会被缓存,除非依赖的响应式 property
变化才会重新计算。注意,如果某个依赖 (比如非响应式 property
) 在该实例范畴之外,则计算属性是不会被更新的。
日常使用
computed: {
drawer() {
try {
// 目前vuex中不存在layout
return this.$store.state.layout.drawer
} catch {
return this.isDrawer
}
},
},
不日常使用
computed:{
// 读取和设置
contentLayoutNav(){
get: () => store.state.appConfig.app.contentLayoutNav,
set: value => {
store.commit('appConfig/UPDATE_CONTENT_LAYOUT_NAV', value)
},
}
}
官网示例
var vm = new Vue({
data: { a: 1 },
computed: {
// 仅读取
aDouble: function () {
return this.a * 2
},
// 读取和设置
aPlus: {
get: function () {
return this.a + 1
},
set: function (v) {
this.a = v - 1
}
}
}
})
vm.aPlus // => 2
vm.aPlus = 3
vm.a // => 2
vm.aDouble // => 4