vue2的特点就是选项式api,如果不得不使用vue2还想在外部使用生命周期钩子函数呢(不使用外部插件)?
1. 响应式
使用 Vue.observable
方法
utils.js
export function useMapLocation(vm){
const mapLocationState = Vue.observable({
loading: false
})
vm.$watch(() => mapLocationState.loading, val => {
// ...
})
return { mapLocationState }
}
index.vue
<script>
export default {
created(){
const { mapLocationState } = useMapLocationLoading(this)
this.mapLocationState = mapLocationState
},
mounted(){
this.mapLocationState.loading = true
}
}
</script>
2. 生命周期钩子
onMounted
钩子依然被耦合到了组件的选项里,如何解耦呢,想在utils中注册呢,能不能使用vm.$onMounted(() =>{})
呢,很抱歉,vue未提供,无法使用。我们需要另辟蹊径,这里举例onMounted,其他同理,直接上代码
index.vue
<script>
export default {
data(){
return {
$hooks: {
onMountedList:[]
}
}
},
created(){
this.$onMounted = (callback) =>{
this.$hooks.onMountedList.push(callback)
}
const { mapLocationState } = useMapLocationLoading(this)
this.mapLocationState = mapLocationState
},
mounted(){
this.$hooks.onMountedList.forEach(onMounted =>onMounted())
}
}
</script>
utils.js
export function useMapLocation(vm){
const mapLocationState = Vue.observable({
loading: false
})
vm.$watch(() => mapLocationState.loading, val => {
// ...
})
vm.$onMounted(() =>{
mapLocationState.loading = false
})
return { mapLocationState }
}
以上的vue代码可以混入到mixin中,进行全局注册,这样所有的组件都可以用了