文末更多精彩内容
1.监听数组和对象
有时候使用 watcher 不能正确触发,很多情况下是因为我们试图监听数组或对象,但没有将 deep 设置为 true
export default {
name: 'namesChange',
props: {
names: {
type: Array,
required: true,
},
},
watch: {
names: {
// 这将让 Vue 知道要在数组内部寻找,如不添加,则不能进行深度监听
deep: true,
handler(newVal,oldVal)
console.log('The list of names has changed!');
2.路由参数解耦
通常在组件中使用路由参数,大多数人会做以下事情。
exportdefault{
methods:{
getParamsId(){
returnthis.$route.params.id
}
}
}
在组件中使用 $route 会导致与其相应路由的高度耦合,通过将其限制为某些 URL 来限制组件的灵活性。正确的做法是通过 props 来解耦。
const router = new VueRouter({
routes: [{
path: /user/:id ,
component: User,
props: true
}]
})
将路由的 props 属性设置为 true 后,组件内部可以通过 props 接收 params 参数。
exportdefault{
props:[id],
methods:{
getParamsId(){
returnthis.id
}
}
}
您还可以通过功能模式返回道具。
const router = new VueRouter({
routes: [{
path: /user/:id ,
component: User,
props: (route) => ({
id: route.query.id
})
}]
})
3.检测元素外部(或内部)的单击
当我们需要检测一个点击是发生在一个特定元素 el 的内部还是外部,通常使用的方法
window.addEventListener('click', e => {
const currtentEl = e.target;
// 检测在el元素的内部还是外部
if (el.contains(currtentEl)) {
// 在el里面点击了
} else {
// 在el外面点击了
获取更多精彩内容:kdocs.cn/l/co5YnU5vIpTm
领取专属 10元无门槛券
私享最新 技术干货