当前位置:网站首页>Mall project pc--- product details page

Mall project pc--- product details page

2022-06-25 02:27:00 Front end young master Jia

Catalog

vue Routing rollover behavior

Exclusive thoughts

Magnifier

  Join the shopping cart operation

Project practice

Promise

characteristic

usage

then

Execution order

expand async/await

Promise Advantages and disadvantages

Promise Method :

Browser cache

Why do you need local storage :

window.sessionStorage

window.localStorage

difference

grammar


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

  1. 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 )
  2. 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 :

  1. Promise Object status changed to Resolved Called when the ( Mandatory )
  2. 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

  1. The data is stored in the user's browser , In the console Application Module .
  2. Set up 、 Easy to read 、 Even page refresh does not lose data
  3. Large capacity ,sessionStorage about 5M、localStorage about 20M
  4. 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

  1. Life cycle To close the browser window

  2. In the same window ( page ) Next, data can be shared

  3. Store and use in the form of key value pairs

window.localStorage

  1. The declaration cycle is permanent , Unless you delete Otherwise, closing the page will also exist

  2. You can have multiple windows ( page ) share ( The same browser can share )

  3. 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()
原网站

版权声明
本文为[Front end young master Jia]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/176/202206242246273950.html