当前位置:网站首页>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()
边栏推荐
- It is said that Yijia will soon update the product line of TWS earplugs, smart watches and bracelets
- Redistemplate operates redis. This article is enough (I) [easy to understand]
- Are programmers from Huawei, Alibaba and other large manufacturers really easy to find?
- 软件测试人员的7个等级,据说只有1%的人能做到级别7
- Uncaught Error: [About] is not a <Route> component. All component children of <Routes> must be a <Ro
- Cusdis - lightweight, privacy first open source comment system | chain of the city
- Lizuofan, co-founder of nonconvex: Taking quantification as his lifelong career
- PE文件基础结构梳理
- Redis
- 如何通过EasyCVR接口监测日志观察平台拉流情况?
猜你喜欢

jwt

Lizuofan, co-founder of nonconvex: Taking quantification as his lifelong career

华为、阿里等大厂程序员真的好找对象吗?

ProcessOn制作ER过程(自定义)

Software testing salary in first tier cities - are you dragging your feet

Left hand dreams right hand responsibilities GAC Honda not only pays attention to sales but also children's safety

【FPGA】串口以命令控制温度采集

DDD concept is complex and difficult to understand. How to design code implementation model in practice?

Experience of epidemic prevention and control, home office and online teaching | community essay solicitation

It is said that Yijia will soon update the product line of TWS earplugs, smart watches and bracelets
随机推荐
How to monitor the log through the easycvr interface to observe the platform streaming?
【Proteus仿真】Arduino UNO+继电器控制照明设备
How to choose a regular and safe foreign exchange trading platform?
做软件安全测试的作用,如何寻找软件安全测试公司出具报告?
Investigation on key threats of cloud computing applications in 2022
02 common codes for Epicor secondary development
实战攻防演练中的四大特点
Computing service network: a systematic revolution of multi integration
基本布局-QHBoxLayout类、QVBoxLayout类、QGridLayout类
疫情防控,居家办公,网上授课之心得 | 社区征文
E - average and median
The role of software security testing, how to find a software security testing company to issue a report?
Four characteristics of actual attack and defense drill
Can automate - 10k, can automate - 20K, do you understand automated testing?
Application of TSDB in civil aircraft industry
|遇到bug怎么分析,专业总结分析来了
MCN机构遍地开花:博主和作者要谨慎签约、行业水很深
华泰证券如何开户能做到万分之一?证券开户安全可靠吗
记一次beego通过go get命令后找不到bee.exe的坑
Resolution of cross reference in IDA