- [ ] 自定义 vue 指令
- [ ] filter
1、 路由参数解耦
通常在组件中使用路由参数,大多数人会做以下事情。
jsx
export default {
methods: {
getParamsId() {
return this.$route.params.id
}
}
}在组件中使用 $route 会导致与其相应路由的高度耦合,通过将其限制为某些 URL 来限制组件的灵活性。正确的做法是通过 props 来解耦。
jsx
const router = new VueRouter({
routes: [{
path: /user/:id ,
component: User,
props: true
}]
})将路由的 props 属性设置为 true 后,组件内部可以通过 props 接收 params 参数。
jsx
export default {
props: [id],
methods: {
getParamsId() {
return this.id
}
}
}您还可以通过功能模式返回道具。
jsx
const router = new VueRouter({
routes: [{
path: /user/:id ,
component: User,
props: (route) => ({
id: route.query.id
})
}]
})2、功能组件
功能组件是无状态的,它不能被实例化,也没有任何生命周期或方法。创建功能组件也很简单,只需在模板中添加功能声明即可。它一般适用于只依赖于外部数据变化的组件,并且由于其轻量级而提高了渲染性能。组件需要的一切都通过上下文参数传递。它是一个上下文对象,具体属性见文档。这里的 props 是一个包含所有绑定属性的对象。
jsx
<template functional>
<div class="list">
<div class="item" v-for="item in props.list" :key="item.id" @click="props.itemClick(item)">
<p>{{item.title}}</p>
<p>{{item.content}}</p>
</div>
</div>
</template>父组件使用
jsx
<template>
<div>
<List :list="list" :itemClick="item => (currentItem = item)" />
</div>
</template>jsx
import List from @/components/List.vue
export default {
components: {
List
},
data() {
return {
list: [{
title: title ,
content: content
}],
currentItem:
}
}
}3、程序化事件监听器
例如,在页面挂载时定义一个定时器,需要在页面销毁时清除定时器。这似乎不是问题。但仔细观察,this.timer 的唯一目的是能够在 beforeDestroy 中获取计时器编号,否则是无用的。
jsx
export default {
mounted() {
this.timer = setInterval(() => {
console.log(Date.now())
}, 1000)
},
beforeDestroy() {
clearInterval(this.timer)
}
}如果可能,最好只访问生命周期挂钩。这不是一个严重的问题,但可以认为是混乱。我们可以通过使用 on 或 once 监听页面生命周期销毁来解决这个问题:
jsx
export default {
mounted() {
this.creatInterval( hello )
this.creatInterval( world )
},
creatInterval(msg) {
let timer = setInterval(() => {
console.log(msg)
}, 1000)
this.$once( hook:beforeDestroy , function() {
clearInterval(timer)
})
}
}使用这种方法,即使我们同时创建多个定时器,也不影响效果。这是因为它们将在页面被销毁后以编程方式自动清除。
4、监听组件生命周期
通常我们使用 $emit 监听组件生命周期,父组件接收事件进行通知。
子组件
jsx
export default {
mounted() {
this.$emit(listenMounted)
}
}父组件
jsx
<template>
<div>
<List @listenMounted="listenMounted" />
</div>
</template>其实有一种简单的方法就是使用@hook 来监听组件的生命周期,而不需要在组件内部做任何改动。同样,创建、更新等也可以使用这个方法。
jsx
<template>
<List @hook:mounted="listenMounted" />
</template>