首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

几个实用的 Vue 开发技巧

文末更多精彩内容

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

  • 发表于:
  • 原文链接https://kuaibao.qq.com/s/20230224A09SYU00?refer=cp_1026
  • 腾讯「腾讯云开发者社区」是腾讯内容开放平台帐号(企鹅号)传播渠道之一,根据《腾讯内容开放平台服务协议》转载发布内容。
  • 如有侵权,请联系 cloudcommunity@tencent.com 删除。

扫码

添加站长 进交流群

领取专属 10元无门槛券

私享最新 技术干货

扫码加入开发者社群
领券