watch:{ $route(newValue, oldValue){ this.setTags(newValue); } },
时间: 2024-02-10 11:47:31 浏览: 19
这段代码是一个 Vue.js 组件中的 Watcher,用于监听 `$route` 对象的变化,并在 `$route` 对象发生变化时执行相应的操作。具体地,它通过 `$route` 对象的变化来判断当前页面的路由信息是否发生变化,如果发生了变化,则调用 `this.setTags(newValue)` 方法,将新的路由信息添加到标签列表中。在 Vue.js 中,Watcher 用于监听响应式数据的变化,并在数据变化时执行相应的操作。当被监听的响应式数据发生变化时,Watcher 会自动执行其绑定的回调函数,并将新值和旧值作为参数传递给回调函数。在这里,`$route` 对象是一个响应式数据,它会在路由发生变化时自动更新,并触发 Watcher 的回调函数执行。
相关问题
怎么优化这段代码export default { data() { return { goodsId: " ", goodsData: [], current: 0, oldScrollTop: 0, scrollTop: 0, searchBgc: " rgba(0, 0, 0, 0.1)", show: false, opacity: 0, flag: true, }; }, mounted() { this.handleScroll(); }, beforeDestroy() { window.removeEventListener("scroll", this.handleScrollFn); //离开当前组件别忘记移除事件监听哦 }, watch: { scrollTop: { handler: function (newValue, oldValue) { clearTimeout(this.timer); this.timer = setTimeout(() => { if (newValue == window.scrollY) { this.oldScrollTop = newValue; if (this.oldScrollTop > 100) { this.show = true; } else { this.show = false; } } else { if (this.oldScrollTop == oldValue) { // console.log("滚动开始"); } } }, 20); }, immediate: true, }, }, methods: { handleScroll() { this.handleScrollFn = () => { this.scrollTop = window.scrollY; }; window.addEventListener("scroll", this.handleScrollFn); }, onClickLeft() { this.$router.go(-1); }, onChange(index) { this.current = index; }, returnFn() { this.$router.go(-1); }, // 加入购物车 joinShopCar() { alert("加入购物车成功"); let shopcarList = JSON.parse(localStorage.getItem("shopcar")) || []; console.log(shopcarList); this.goodsData.num = 1; this.goodsData.isChecked = false; let ind = shopcarList.findIndex((ele) => { return ele.id == this.goodsId; }); console.log(ind); // 如果有相同的返回该数据的下标,没有则返回-1 if (ind != -1) { shopcarList[ind].num++; } else { shopcarList.push(this.goodsData); } localStorage.setItem("shopcar", JSON.stringify(shopcarList)); this.$router.push("/shopcar"); }, // 立即结算 payFn() { localStorage.setItem("goodspay", JSON.stringify(this.goodsData)); this.$router.push("/pay"); }, }, async created() { this.goodsId = this.$route.query.id; try { let { data } = await getGoodsDetailApi(this.goodsId); this.goodsData = data.data.goodsData; console.log(this.goodsData); } catch (err) { console.log(err); } }, };
这段代码可以考虑进行以下优化:
1. 将方法中的注释删除,因为这些注释并没有提供太多有用的信息,反而会干扰代码的阅读。
2. 将所有的变量定义在最上面,以便于阅读和维护。同时,可以将一些不经常使用的变量定义为局部变量,以减少内存的占用。
3. 将一些方法提取出来,封装成单独的函数并放在外部,以提高代码的可复用性和可读性。
4. 为了提高代码的性能,可以将一些异步操作放到 created 钩子函数中,以免影响页面的渲染速度。
5. 对于方法中的一些重复代码,可以进行优化,如将相同部分提取出来,避免重复代码的出现。
6. 对于一些可能产生副作用的操作,如 alert(),应该尽量避免在代码中使用,以免影响用户体验。
下面是优化后的代码:
```
<template>
<!-- 模板代码 -->
</template>
<script>
import { getGoodsDetailApi } from "@/api"; // 导入 api 接口
export default {
data() {
return {
goodsId: " ",
goodsData: [],
current: 0,
oldScrollTop: 0,
scrollTop: 0,
searchBgc: "rgba(0, 0, 0, 0.1)",
show: false,
opacity: 0,
flag: true,
timer: null,
};
},
mounted() {
this.handleScroll();
},
beforeDestroy() {
window.removeEventListener("scroll", this.handleScrollFn);
},
watch: {
scrollTop: {
handler: function (newValue, oldValue) {
clearTimeout(this.timer);
this.timer = setTimeout(() => {
if (newValue == window.scrollY) {
this.oldScrollTop = newValue;
this.show = this.oldScrollTop > 100;
} else {
if (this.oldScrollTop == oldValue) {
// 滚动开始
}
}
}, 20);
},
immediate: true,
},
},
methods: {
// 监听滚动事件
handleScroll() {
this.handleScrollFn = () => {
this.scrollTop = window.scrollY;
};
window.addEventListener("scroll", this.handleScrollFn);
},
// 返回上一页
onClickLeft() {
this.$router.go(-1);
},
// 切换商品详情页
onChange(index) {
this.current = index;
},
// 返回上一页
returnFn() {
this.$router.go(-1);
},
// 加入购物车
joinShopCar() {
if (confirm("确定要加入购物车吗?")) {
let shopcarList = JSON.parse(localStorage.getItem("shopcar")) || [];
this.goodsData.num = 1;
this.goodsData.isChecked = false;
let ind = shopcarList.findIndex((ele) => {
return ele.id == this.goodsId;
});
if (ind != -1) {
shopcarList[ind].num++;
} else {
shopcarList.push(this.goodsData);
}
localStorage.setItem("shopcar", JSON.stringify(shopcarList));
this.$router.push("/shopcar");
}
},
// 立即结算
payFn() {
localStorage.setItem("goodspay", JSON.stringify(this.goodsData));
this.$router.push("/pay");
},
// 获取商品详情数据
async getGoodsDetail() {
try {
let { data } = await getGoodsDetailApi(this.goodsId);
this.goodsData = data.data.goodsData;
console.log(this.goodsData);
} catch (err) {
console.log(err);
}
},
},
created() {
this.goodsId = this.$route.query.id;
this.getGoodsDetail();
},
};
</script>
```
vue watch监听函数
vue中的watch监听函数用于观察和监听页面上的vue实例中的数据变化。当需要在数据变化时执行异步操作或高性能消耗的操作时,watch是最佳选择。在使用watch监听函数时,可以监听字符串、监听对象和监听路由。
监听字符串的代码示例:
```javascript
watch: {
dataPropertyName: function(newValue, oldValue) {
// 在数据变化时执行的操作
}
}
```
监听对象时,需要添加`deep: true`,才能深入底层实时监听对象的变化。如果没有添加,对象是无法被监听到变化的。
```javascript
watch: {
dataPropertyName: {
handler: function(newValue, oldValue) {
// 在数据变化时执行的操作
},
deep: true
}
}
```
监听路由时,可以使用`$route`来监听当前路由的变化。
```javascript
watch: {
'$route': {
handler: function(newValue, oldValue) {
// 在路由变化时执行的操作
},
deep: true,
immediate: true
}
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)