lisa的个人博客

慢慢理解世界,慢慢更新自己

0%

vue实战小技巧

本片文章借鉴自掘金的’前端进击者’,仅用作个人学习使用。

外部监听组件生命周期函数

使用场景:
应用第三方组件,需要监听第三方组件数据变化,但是没有提供change事件,so, 这时候就需要你在外部去监听组件的updated钩子函数

代码实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<template >
<!--通过 @hook: updated = "xxx"监听组件的updated生命钩子函数-- >
<!--组件的所有生命周期钩子函数都可以通过这种方式去实现监听-- >
<c-component @hook: updated = "$_handleSelectUpdated" > </c-component>
</template >

<script>
export default {
data() {
return {}
},
components: {
CComponent
},
methods: {
$_handleSelectUpdated() {
console.log('c组件数据已更新');
}
}
};
</script>
<style lang = "less" >

</style>

内部监听组件的生命周期函数

场景需要:
监听事件和销毁事件放在一起,增加可读性

代码实现:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<template>
<div class = 'chart'></div>
</template>

<script>
export default {
data() {
return {}
},
mounted() {
this.$chart = echart.init(this.$el);
// 图表配置,请求赋值数据等操作
window.addEventListener('resize', this.$_handleResizeChart);
// 通过hook监听组件销毁钩子,并取消监听事件 $once 只触发一次,也可以使用$on进行监听。
this.$once('hook:beforeDestroy', function() {
window.removeEventListener('resize', this.$_handleResizeChart);
})
},
methods: {
$_handleResizeChart() {
// this.$chart.resize();
}
}
};
</script>

自己动手封装一个vue状态管理

在前端项目中,组件之间需要共享数据状态,一般情况都会选择使用vuex,但是对于小型项目来说是不推荐使用vuex,因为它是有点繁琐且冗余,这时候我们就可以使用vue2.6提供的api Vue.observable手动打造一个vuex。

代码实现:

创建store:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import Vue from 'vue';

export const store = Vue.observable({
userName: 'lisa',
userAge: 18
});

export const mutations = {
setUserInfo(name) {
store.userName = name;
},
setUserAge(age) {
store.userAge = age;
}
};

在main.js中引入,方法挂到vue身上,可以全局使用

1
2
3
4
5
6
7
8
import Vue from 'vue'
import {
store,
mutations
} from '@/store/index.js';

Vue.prototype.$store = store;
Vue.prototype.$mutations = mutations;

组件中使用:

1
2
3
4
5
6
7
8
9
< script >
export default {
data: {},
mounted() {
this.$mutations.setUserAge('19'); // 赋值操作
console.log(this.$store.userAge) // 读取操作
}
}
</script>