当前位置:网站首页>Mall project pc--- product details page
Mall project pc--- product details page
2022-06-25 02:27:00 【Front end young master Jia】
Catalog
Join the shopping cart operation
Promise Advantages and disadvantages
Why do you need local storage :
vue Routing rollover behavior
Use front-end routing , When switching to a new route , Want the page to scroll to the top , Or keep the original rolling position , It's like reloading a page . vue-router Can do , And better , It allows you to customize how the page scrolls during route switching .
const router = createRouter({
scrollBehavior(to, from, savedPosition) {
// Always scroll to the top
return { top: 0 }
},
})Exclusive thoughts
The clicked item is true The other items are false
changeActive(val, list) {
// Current click item And the entire loop array
console.log(val, list);
// Traverse all attribute values as 0 No highlight
list.forEach((ele) => {
ele.isChecked = 0;
});
// The clicked item is 1
val.isChecked = 1;
},Magnifier
<template>
<div class="spec-preview">
<img :src="skuImageList[currentIndex].imgUrl" />
<div class="event" @mousemove="hadleer"></div>
<!-- Big picture -->
<div class="big">
<img :src="skuImageList[currentIndex].imgUrl" ref="big" />
</div>
<!-- Mask -->
<div class="mask" ref="mask"></div>
</div>
</template>
<script>
export default {
name: "Zoom",
props: ["skuImageList"],
data() {
return {
currentIndex: 0,
};
},
mounted() {
this.$bus.$on("getIndex", (index) => {
this.currentIndex = index;
console.log(this.currentIndex);
});
},
methods: {
hadleer(event) {
// Move the mouse in to get the mask
let mask = this.$refs.mask;
let big = this.$refs.big;
let left = event.offsetX - mask.offsetWidth / 2;
let top = event.offsetY - mask.offsetHeight / 2;
if (left <= 0) left = 0;
if (left >= mask.offsetWidth) left = mask.offsetWeight;
if (top <= 0) top = 0;
if (top >= mask.offsetHeight) top = mask.offsetHeight;
mask.style.left = left + "px";
mask.style.top = top + "px";
big.style.left = -2 * left + "px";
big.style.top = -2 * top + "px";
},
},
};
</script>
<style lang="less">
.spec-preview {
position: relative;
width: 400px;
height: 400px;
border: 1px solid #ccc;
img {
width: 100%;
height: 100%;
}
.event {
width: 100%;
height: 100%;
position: absolute;
top: 0;
left: 0;
z-index: 998;
}
.mask {
width: 50%;
height: 50%;
background-color: rgba(0, 255, 0, 0.3);
position: absolute;
left: 0;
top: 0;
display: none;
}
.big {
width: 100%;
height: 100%;
position: absolute;
top: -1px;
left: 100%;
border: 1px solid #aaa;
overflow: hidden;
z-index: 998;
display: none;
background: white;
img {
width: 200%;
max-width: 200%;
height: 200%;
position: absolute;
left: 0;
top: 0;
}
}
.event:hover ~ .mask,
.event:hover ~ .big {
display: block;
}
}
</style>Join the shopping cart operation
Project practice
The request to add to the shopping cart is placed in vuex in The request interface only returns the status code , We need to judge the distribution vuex Result
vuex Because of the use of async await call AsyncAddOrUpdataShopCart return promise
We need to do more return promis Instance status code200 If the return is not empty, it means success , Otherwise, it returns the failed status
async AsyncAddOrUpdataShopCart({
commit
}, {
skuId,
skuNum
}) {
let result = await axios.reqAddOrUpdataShopCart(skuId, skuNum)
// The server is successfully added to the shopping cart modify promise Status is success The successful value is ok
if (result.code == 200) {
return 'ok'
} else {
return Promise.reject(new Error('false'))
}
}
}Page waiting promise The state of Use try catch Handle
// Add to cart
async addShopCar() {
// Call return promise retrun If the string is not empty, the jump will be successful The failure of the promise Tips
try {
let result = await this.$store.dispatch('AsyncAddOrUpdataShopCart', {
skuId: this.$route.params.skuId,
skuNum: this.skuNum
})
console.log(result);
} catch (err) {
console.log(err);
}
}
},Promise
Promise Is a solution to asynchronous programming , More than traditional solutions —— Callback functions and events — More reasonable and powerful . It was first proposed and implemented by the community ,ES6 It's written into the language standard , Unify usage , And provides Promise object .
characteristic
- The state of the object is not affected by the outside world (3 States )
- Pending state ( Have in hand )
- Fulfilled state ( Have succeeded )
- Rejected state ( Failed )
- Once the state changes, it won't change again ( Two states change : Success or failure )
- Pending -> Fulfilled
- Pending -> Rejected
usage
establish Promise example
var promise = new Promise(function(resolve, reject){
// ... some code
if (/* Asynchronous operation succeeded */) {
resolve(value);
} else {
reject(error);
}
})
Promise The constructor takes a function as an argument , The two parameters of this function are resolve and reject. They are two functions , from JavaScript The engine provides , Don't deploy yourself .
resolve Role is to Promise Object state is determined by “ Hang in the air ” Turn into “ success ”, That is to say Pending -> Fulfilled, Called when the asynchronous operation succeeds , The result of the asynchronous operation is passed as a parameter ; and reject The function is to set Promise Object state is determined by “ Hang in the air ” Turn into “ Failure ”, That is to say Pending -> Rejected, Called when an asynchronous operation fails , The result of the asynchronous operation is passed as a parameter .
then
Promise After instance generation , You can use then Two callback methods are specified respectively .then Method can take two callback functions as parameters :
- Promise Object status changed to Resolved Called when the ( Mandatory )
- Promise Object status changed to Rejected Called when the ( Optional )
Examples of basic usage
function sleep(ms) {
return new Promise(function(resolve, reject) {
setTimeout(resolve, ms);
})
}
sleep(500).then( ()=> console.log("finished"));
This code defines a function sleep, After calling , Waiting for the specified parameter (500) In milliseconds, execute then The function in . It is worth noting that ,Promise Execute as soon as new .
Execution order
Next, let's explore its execution order , Look at the following code :
let promise = new Promise(function(resolve, reject){
console.log("AAA");
resolve()
});
promise.then(() => console.log("BBB"));
console.log("CCC")
// AAA
// CCC
// BBB
After execution , We find that the output order is always AAA -> CCC -> BBB. indicate , stay Promise It will be executed immediately after creation , therefore The first output AAA. then ,then The callback function specified by the method will not be executed until all synchronization tasks of the current script are executed , therefore BBB The final output .
To mix with a timer, first look at an example :
let promise = new Promise(function(resolve, reject){
console.log("1");
resolve();
});
setTimeout(()=>console.log("2"), 0);
promise.then(() => console.log("3"));
console.log("4");
// 1
// 4
// 3
// 2
You can see , The result output order is always :1 -> 4 -> 3 -> 2.1 And 4 There is no need to say the order of , and 2 And 3 First, the output Promise Of then, Then output timer task . The reason is Promise Belong to JavaScript Internal tasks of the engine , and setTimeout It's the browser API, The internal task of the engine is higher than that of the browser API Mission , So this result .
expand async/await
async
seeing the name of a thing one thinks of its function , asynchronous .async Function pair Generator Function improvements ,async Function must return Promise, Let's get everything back Promise All functions of can be regarded as asynchronous functions . The characteristics are reflected in the following four points :
- Built in actuator
- Better semantics
- Wider applicability
- The return value is Promise
await
seeing the name of a thing one thinks of its function , wait for . Under normal circumstances ,await The command is followed by a Promise object , Returns the result of the object . If not Promise object , Just return the corresponding value directly . The other case is ,await The command is followed by a thenable object ( By defining then Object of method ), that await Will equate it with Promise object .
Let's look at the examples first :
function sleep(ms) {
return new Promise(function(resolve, reject) {
setTimeout(resolve,ms);
})
}
async function handle(){
console.log("AAA")
await sleep(5000)
console.log("BBB")
}
handle();
// AAA
// BBB (5000ms after )
We define functions sleep, Return to one Promise. And then in handle Add... Before the function async key word , This defines a async function . In this function , utilize await To wait for a Promise.
Promise Advantages and disadvantages
| advantage | shortcoming |
|---|---|
| Resolve callback | Unable to monitor status |
| call chaining | New is executed immediately and cannot be cancelled |
| Reduce the nested | Internal error cannot be thrown |
Promise Method :
Common methods are 5 in :then()、catch()、all()、race()、finally().
1.then()
Take two callback functions as arguments , The first parameter indicates to execute when successful , The second parameter indicates to execute when failure occurs , When returning, a new promise Real series of .
2.catch()
amount to then The second argument to the method .
3.all()
Take an array as your own parameter , Every item in the array is a promise object , When each of the array promise In the state of resolved when ,all The state of the method becomes resolved, One becomes rejected, that all The state of the method becomes rejected.
4.race()
He and all The method is the same , Take an array as your own parameter , But different times he finished first promise To define the immediate state , Assuming the first state resolved, that race The state of the method is resolved, On the contrary .
5finally()
He doesn't care promise Any state will be executed in the , He doesn't accept any parameters .
Browser cache
Why do you need local storage :
- The data is stored in the user's browser , In the console Application Module .
- Set up 、 Easy to read 、 Even page refresh does not lose data
- Large capacity ,
sessionStorageabout 5M、localStorageabout 20M - Only strings can be stored , You can put objects
JSON.stringify()Store after encoding
There are two types of ground storage , One is sessionStorage, as well as localStorage. So what are the similarities and differences ?
window.sessionStorage
Life cycle To close the browser window
In the same window ( page ) Next, data can be shared
Store and use in the form of key value pairs
window.localStorage
The declaration cycle is permanent , Unless you delete Otherwise, closing the page will also exist
You can have multiple windows ( page ) share ( The same browser can share )
Store and use in the form of key value pairs
difference
The biggest difference : Life cycle difference ,sessionStorage After the browser page storing data closes, the stored data disappears , however localStorage Even if the page where the browser stores data is closed , And the data won't be lost , How to delete localStorage The stored data ? Use localStorage.removeItem(key) and localStorage.clear() Statement to delete .
The same thing : Both are used to store data and the code syntax structure is similar . Let's talk about the code for storing data structures in detail :
grammar
- Store the data : sessionStorage.setItem(key, value)
- get data :sessionStorage.getItem(key)
- Delete data :sessionStorage.removeItem(key)
- Empty data :( Get rid of everything ) sessionStorage.clear()
边栏推荐
- 3 years of testing experience. I don't even understand what I really need on my resume. I need 20K to open my mouth?
- 消息称一加将很快更新TWS耳塞、智能手表和手环产品线
- MCN机构遍地开花:博主和作者要谨慎签约、行业水很深
- Beescms website penetration test and repair comments "suggestions collection"
- Android Internet of things application development (smart Park) - set sensor threshold dialog interface
- 同花顺是正规平台吗?同花顺开户安全吗
- It's 2022, and you still don't know what performance testing is?
- 记一次beego通过go get命令后找不到bee.exe的坑
- 2022-06-24:golang选择题,以下golang代码输出什么?A:1;B:3;C:4;D:编译失败。 package main import ( “f
- EasyCVR平台EHOME协议接入,视频播放出现断流是什么原因?
猜你喜欢

做软件安全测试的作用,如何寻找软件安全测试公司出具报告?

当他们在私域里,掌握了分寸感

The role of software security testing, how to find a software security testing company to issue a report?

疫情防控,居家办公,网上授课之心得 | 社区征文

Talking about the advantages of flying book in development work | community essay solicitation
Cusdis - lightweight, privacy first open source comment system | chain of the city

一线城市软件测试工资——你拖后腿了吗

背了八股文,六月赢麻了……

【直播回顾】战码先锋第七期:三方应用开发者如何为开源做贡献

When they are in private, they have a sense of propriety
随机推荐
Investigation on key threats of cloud computing applications in 2022
指南针靠谱吗?开证券账户安全吗?
Random list random generation of non repeating numbers
Please run IDA with elevated permissons for local debugging.
Computing service network: a systematic revolution of multi integration
【第26天】给定 n 个元素的升序数组nums,求实现一个函数在nums中寻找target的下标 | 初识二分查找
AI服装生成,帮你完成服装设计的最后一步
如何卸载cuda
[mobile terminal] design size of mobile phone interface
psql 列转行
EasyCVR平台EHOME协议接入,视频播放出现断流是什么原因?
内网学习笔记(6)
[day 26] given the ascending array nums of n elements, find a function to find the subscript of target in nums | learn binary search
[live review] battle code pioneer phase 7: how third-party application developers contribute to open source
Four characteristics of actual attack and defense drill
beescms网站渗透测试和修复意见「建议收藏」
3 years of testing experience. I don't even understand what I really need on my resume. I need 20K to open my mouth?
Android Internet of things application development (smart Park) - set sensor threshold dialog interface
Cusdis - lightweight, privacy first open source comment system | chain of the city
The ecosystem of the yuan universe