当前位置:网站首页>PC e-commerce platform - search module

PC e-commerce platform - search module

2022-06-21 21:04:00 Front end young master Jia

Catalog

vuex Modularity in

Object.assign() usage

watch monitor

Array methods splice And split

splice

split() Method

Array weight removal

Custom pager


vuex Modularity in

vuex Use the trilogy    

Write requests

page dispatch distributed actions Save to vuex in (actions Send the request commit notice mutations ,mutations Modify warehouse data )

Page fetching data ( Auxiliary function mapState Map to calculated properties )

Big warehouse

import Vue from 'vue'
import Vuex from 'vuex'
import home from './home'
import search from './search'
// You need to use plug-ins 
Vue.use(Vuex)


//  Object exposes a store An instance of a class 
export default new Vuex.Store({
    modules: {
        home,
        search
    }
})

  Small warehouse

import axios from '@/api'
// home  Small warehouse of components 
const state = {
    // The default initial value depends on the server data format 
    CategoryList: []
}
const mutations = {
    CategoryList(state, payload) {
        state.CategoryList = payload
    }
}
const actions = {
    // adopt api Interface to get data 
    async AstncCategoryList({ commit }) {
        let { data, code } = await axios.CategoryList();
        if (code !== 200) return
        commit('CategoryList', data)
    }
}
const getters = {}
export default {
    state,
    mutations,
    actions,
    getters
}

  mount

// Import warehouse 
import store from './store'
new Vue({
  render: h => h(App),
  // There will be one more on the component store Properties of 
  store
}).$mount('#app')

  page

state Central sub module The calculation property is mapped to the page variable

 import { mapState } from "vuex";
 computed: {
    ...mapState({
      // What you need on the right is a function , When using this calculation property , The function on the right will execute once immediately 
      // Into a state
      CategoryList: (state) => state.home.CategoryList,
    }),
  },

  actions No modules

  mounted() {
    // notice vuex Send the request , The acquired data is stored in vuex in 
    this.$store.dispatch("AstncCategoryList");
  },

getters For simplifying data

// Compute properties   Simplified data 
const getters = {
    // Of the current warehouse state
    goodsList(state) {
        // In case the network delays returning undefined
        return state.SearchList.goodsList || []
    }
}

Object.assign() usage

1.Object.assign() Method is used to assign the values of all enumerable properties from one or more source objects to the target objects . It will return the target object .
2.Object.assign The method is shallow copy , Not a deep copy . The copy of the target object will get the reference of this object
3. grammar :Object.assign(target, …sources)

let aaa = {
 text: 2,
 value: 11,
}

let bbb = {
  text: 3
}

let ccc = Object.assign(aaa,bbb) // aaa Target audience , bbb Source object 

console.log(aaa) //3 11
console.log(bbb) //3
console.log(ccc) //3 11

summary :Object.assign() When merging objects , If the same key name exists , Values are different , Then the merged value (ccc) The value of this key is the source object (bbb) Value , And the target object (aaa) The value of

watch monitor

This is the problem of asynchronous requests , For example, we request a data asynchronously , However, the main thread is still running normally , When we hear the data request coming , Have the data , Then you can do other operations , This is the meaning of monitoring

watch There are several properties in monitoring :immediate,deep and handler

watch: {
    // monitor carouselList Status changes 
    carouselList: {
      // Deep monitoring 
      deep:true
      // Monitor now 
      immediate:true
      // Listen to the carouselList The state has changed 
      handler((newValue, oldValue){
        // The next operation after listening to the data 
      }
   }      
}

Array methods splice And split

splice

splice() The main purpose of is to insert items into the middle of an array , There are three ways :

1、 Delete : You can delete any number of items , You only need to specify two parameters : The location of the first item to delete and the number of items to delete .

2、 Insert : You can insert any number of items... Into a specified location , Just provide three parameters : The starting position 、0( Number of items to delete )、 And the item to insert .

3、 Replace : You can insert any number of items... Into a specified location , Delete any number of items at the same time , Specify three parameters : The starting position 、 Number of items to delete 、 And any number of items to insert .

splice() Method always returns an array , The array contains the items deleted from the original array ( If nothing is deleted , Returns an empty array )

Code display method :

var colors =["red","green","blue"];
var removed = colors.splice(0,1);// Delete the first item 
console.log(colors);
console.log(removed);
 
removed = colors.splice(1,0,"yellow","blank");// From the position 1 Insert two 
console.log(colors);
console.log(removed);
 
removed = colors.splice(1,1,"yellow","blank");// Insert two , Replace with 
console.log(colors);
console.log(removed);
————————————————
[ 'red' ]
[ 'green', 'yellow', 'blank', 'blue' ]
[]
[ 'green', 'yellow', 'blank', 'blank', 'blue' ]
[ 'yellow' ]

split() Method


split() Method is used to put a character string Split into string arrays .

separator Parameters : Required . String or Regular expressions , Split from where specified by this parameter stringObject.
howmany Parameters : Optional . This parameter specifies the maximum length of the returned array . If this parameter is set , No more substrings will be returned than the array specified by this parameter . If the parameter is not set , The entire string will be split , Regardless of its length

"2:3:4:5".split(":")    
// Will return ["2", "3", "4", "5"]

"|a|b|c".split("|") 
// Will return ["", "a", "b", "c"]
"hello".split("")   
// You can go back to  ["h", "e", "l", "l", "o"], Split words 

"hello".split("", 3)    
// You can go back to  ["h", "e", "l"], Take the first three letters of the word 

Array weight removal

utilize set Unique characteristics of structure member values

 var arr = [100, 20, 30, 50, 30, 100, 20, 50];//[100,20,30,50]
 var arrSet = new Set(arr);
 //arrSet That is, an array without repeating elements 

// Traverse the old array , Then take the old array to query the new array , If the element does not appear in the new array , Let's add , Otherwise, do not add

// With the new array indexOf( Array elements ), If the return is -1 It means that there is no such element in the new array


	function unique(arr){
	    var newarr = [];
		for(i=0;i<arr.length;i++){
			if(newarr.indexOf(arr[i]) === -1){
			newarr.push(arr[i]);
			    }	
			}
			return newarr;	
	    }
			var arr1 =  unique(['a','v','a']);
			console.log(arr1)
     

Custom pager

  • The e-commerce platform shows a lot of data at the same time, reducing server pressure by using paging
  • We need to know how many we are now pageNo Field , Represents the current number of pages
  • How many pieces of data does each need to display pageSize character
  • How many pieces of data are there total  【 You can see how many pages the pager has 】
  • Number of consecutive pages :5|7【 Odd number 】continues
  •    @getPageNo="getPageNo" Get the current number of pages

a key : Calculation start End consecutive page numbers ( Add... In the middle of the current page 2 Or minus 2 )

<template>
  <div class="pagination">
    <button :disabled="pageNo == 1" @click="$emit('getPageNo', pageNo - 1)">
       The previous page 
    </button>
    <button
      v-if="statrtNumAndEndNum.start > 1"
      @click="$emit('getPageNo', 1)"
      :class="{ active: pageNo == 1 }"
    >
      1
    </button>

    <button v-if="statrtNumAndEndNum.start > 2">···</button>
    <!-- v-for You can traverse objects   Numbers   character string   Array 
     Number of page numbers at the end of traversal ( As long as it is greater than or equal to the number of starting pages, other hidden pages )
    -->
    <button
      v-for="(page, index) in statrtNumAndEndNum.end"
      :key="index"
      @click="$emit('getPageNo', page)"
      :class="{ active: pageNo == page }"
      v-if="page >= statrtNumAndEndNum.start"
    >
      {
   { page }}
    </button>

    <button v-if="statrtNumAndEndNum.end < totalPage - 1">···</button>
    <button
      v-if="statrtNumAndEndNum.end < totalPage"
      @click="$emit('getPageNo', totalPage)"
      :class="{ active: pageNo == totalPage }"
    >
      {
   { totalPage }}
    </button>
    <button
      :disabled="pageNo == totalPage"
      @click="$emit('getPageNo', pageNo + 1)"
    >
       The next page 
    </button>

    <button style="margin-left: 30px"> common  {
   { total }}  strip </button>
  </div>
</template>

<script>
//:pageNo="1"  Current page 
//:pageSize="3" // How many on a page 
//:total="91" // How many in all 
//:continues="5" // Number of consecutive pages 
export default {
  name: "pagination",
  props: ["pageNo", "pageSize", "total", "continues"],
  computed: {
    // Calculate how many pages 
    totalPage() {
      // Round up to calculate how many pages 
      return Math.ceil(this.total / this.pageSize);
    },
    //  Calculate the number of consecutive pages 
    statrtNumAndEndNum() {
      const { continues, pageNo, totalPage } = this;
      //  Store the start and end numbers 
      let start = 0,
        end = 0;
      // The number of consecutive pages must be at least 5( The only special case is 4 page )
      if (continues > totalPage) {
        start = 1;
        end = totalPage;
      } else {
        // The total number of pages must be greater than 5
        //  For example, the current is 8   Continuous for 5       // 6-7 8  9-10 5(8-5/2=8-2=6)
        //  For example, the current is 8   Continuous for 7       // 5-6-7 8  9-10-11(8-3=5)
        start = pageNo - parseInt(continues / 2);
        end = pageNo + parseInt(continues / 2);
        // exclude start by 0 Or negative 
        if (start < 1) {
          start = 1;
          end = continues;
        }
        // Exclude cases that exceed the total number of pages 
        if (end > totalPage) {
          end = totalPage;
          // If it is 31 page   (27-28-29-30  31)
          // If it is 29 page   (27-28-29  30  31)
          start = totalPage - continues + 1; //31-5+1
        }
      }
      return { start, end };
    },
  },
};
</script>

<style lang="less" scoped>
.pagination {
  text-align: center;
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
  .active {
    background: skyblue;
  }
}
</style>

原网站

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