Study notes_ Lemon

Study notes

  • 1. Interface request status value

    100: Temporary response
    
    200: success
    
    300: redirect
    
    400: Access error
    
    500: Server error; 502 no response
    
  • 2.css Style
    Hide slider:

    ul::-webkit-scrollbar { display: none;}
    

    Control placeholder:

    :placeholder-shown
    

    Invalid tr label set for table:

    border-collapse: collapse;
    

    Hide the small eyes of the input password box:

    ::-ms-reveal { display: none;}
    

    input cursor color:

    input{caret-color:red;}
    
  • 3.js
    Print this page:

    <el-button type="success" class @click="$print">
    

    Determine whether it is an element node:

    node.nodeType==1;(1: Element node, 2: attribute node; 3: Text node)
    

    Judgment type:

    Object.prototype.toString.call(parameter)
    

    Get custom properties:

    element.dataset / element.getAttribute
    

    Single line text out of hiding:

    width: 500px;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    

    Multiline text out of hiding:

    overflow: hidden;
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 4;
    

    Judgment undefined:

    typeof(exp) == 'undefined'
    

    src dynamic splicing in img:

    require(`../../assets/img/icon-${item.icon}.png`)
    

    String to JSON object / JSON object to string:

    JSON.parse() / JSON.stringify()
    

    label invalid:

    for corresponding id Not unique
    

    Check whether there is a specified attribute in its own attribute:

    Object.hasOwnProperty()
    

    Keep n decimal places

    Number(num).toFixed(n)
    

    apply gets the maximum and minimum values of the array:

    const arr = [15, 6, 12, 13, 16];
    const max = Math.max.apply(Math, arr); // 16
    const min = Math.min.apply(Math, arr); // 6
    

    Array summation, maximum, minimum

    //Sum
    array.reduce((a,b) => a+b);
    //Maximum
    array.reduce((a,b) => a>b?a:b);
    //minimum value
    array.reduce((a,b) => a<b?a:b);
    

    Remove duplicate values

    const array  = [5,4,7,8,9,2,7,5];
    array.filter((item,idx,arr) => arr.indexOf(item) === idx);
    // or
    const nonUnique = [...new Set(array)];
    // Output: [5, 4, 7, 8, 9, 2]
    
    
    

    Determines whether an object has a specified object

    Object.hasOwn(sert,'aaa')  //Used instead of object prototype. hasOwnProperty
    
    
    

    Gets an array of key value pairs in an object

    const obj = {name:"123",age:12};
    console.log(Object.entries(obj))  // [["name","123"],["age","12"]]
    

    Fill some strings before and after to achieve some formatting effect padStart padEnd

    //The maximum length to be filled in parameter 1 and the characters to be filled in parameter 2. The default is space filling.
    const message = "Hello World"
    const newMessage = message.padStart(15, "*").padEnd(20, "-")
    console.log(newMessage) // ****Hello World-----
    //If the maximum length of the padding is less than the length of the original string, the original string will be output.
    const message = "Hello World"
    console.log(message.padStart(1, 0)) //Hello World
    //If the sum of the length of the complement string and the original string exceeds the maximum length, the complement string exceeding the number of digits will be truncated.
    '12'.padStart(10, 'YYYY-MM-DD') // "YYYY-MM-12"
    '09-12'.padStart(10, 'YYYY-MM-DD') // "YYYY-09-12"
    
    

    Flatten the nested array into a one-dimensional array. This method returns a new array

    //Parameter indicating how many layers of the array need to be expanded. The default value is 1.
    [1, 2, [3, [4, 5]]].flat() // [1, 2, 3, [4, 5]]
    [1, 2, [3, [4, 5]]].flat(2) // [1, 2, 3, 4, 5]
    //If you want to convert to a one-dimensional array no matter how many layers of nesting, you can use the Infinity keyword as a parameter.
    [1, [2, [3]]].flat(Infinity) // [1, 2, 3]
    //If the original array has empty bits, the flat() method skips the empty bits.
    [1, 2, , 4, 5].flat() // [1, 2, 4, 5]
    
    

    Through object Entries converts an object into entries

    const obj = {
      name: "zh",
      age: 22
    }
    const entries = Object.entries(obj)
    const newObj = Object.fromEntries(entries)
    console.log(newObj) //{ name: 'zh', age: 22 }
    
    

    Before es11, we calculated by 𞓜. But it will have some problems. When the previous operand is 0, "" etc., the second operand will still be assigned.

    const foo = 0
    const bar1 = foo || "default value"
    const bar2 = foo ?? "defualt value"
    console.log(bar1, bar2) // default value 0
    
    

    Converts a query string into an object

    const queryString = 'name=zh&age=2'
    const queryParams = new URLSearchParams(queryString)
    console.log(queryParams)  // {'name'=>'zh','age'=>'22'}
    const paramObj = Object.fromEntries(queryParams)
    console.log(paramObj);
    
  • 4.jq
    Event delegation:

    $("ul").on("click","li.box",function () {})
    

    Get whether the checkbox radio box is selected:

    $("input name='reply']:checked").val()
    
  • 5.vue2
    Force re rendering of data:

    this.$forceUpdate()
    

    Invalid set height:

    html,body,#app {height: 100%;}
    

    Write click event in sub component:

    @click.native="click()"
    

    vue parent component invokes rule validation of child component's form:

    this.$refs["SelectTime"].$refs.ruleForm.validate(async (valid) => {  })
    

    props parent to child:

    props:{ title:{ type:Object,default:()=>{ return '123' } } }
    

    watch depth monitoring:

    firstName:{handler:function(newVal,oldVal){},deep:true}
    

    Get element height:

    this.$refs.slideBox[0].offsetHeight
    

    Throttling through custom attributes:

        <button v-debounce>determine</button>
    
        import Vue from "vue";
    
        Vue.directive("debounce", {
    
          //Throttling implementation
    
          inserted: function(el, binding) {
    
            el.addEventListener("click", () => {
    
              if (!el.disabled) {
    
                el.disabled = true;
    
                setTimeout(() => {
    
                  el.disabled = false;
    
                }, binding.value || 3000);
    
              }
    
            });
    
          }
    
        });
    
  • 6.vue3
    Get ref:

    const MyHome = ref<HTMLElement|null>(null)
    

    Reference to third-party component libraries:

    declare global { interface Window {  vrv: any; }} 
    perhaps 
    declare var vrv: any;=>(shims-vue.d.ts)
    [.eslintrc.js]in globals:{vrv:true};
    

    To add a global variable to an ESLint rule:

    .eslintrc.js in globals
    

    Error in getting value from parent to child / props:

    list: {type: Array,default:null,},
    

    Pass values from child components to parent components:

    context.emit("children",'123'); 
    You also need to define
    emits: emits: ["children"],
    

    Invalid dynamic rendering url picture:

    url: require("../../assets/img/exam/img-1.png"),
    

    Using vuex

    import { useStore } from "vuex";
    let store = useStore();
    store.state.annualCheck.otherData
     use mutations Method of
    store.commit("annualCheck/examTimeChange", number);
    use actions Method of
    store.dispatch("user/setuser", userObj);
    
    
  • 7.typescript
    Event get parameter object

    function text(item: { objType: string; id: string; }){   }
    
    
  • 8. Regular expression
    Get the picture address in rich text and replace it/

    str = str.replace(/src="(\.\.\/)*(\w+\/)+\w+\.(bmp|jpg|png|tif|gif|pcx|tga|exif|fpx|svg|psd|cdr|pcd|dxf|ufo|eps|ai|raw|WMF|webp|jpeg)/gi,v=>{
      v = v.replace(/\.\.\//,'10.0.0.72:8080/common')
      return v;
    })
    
  • 9.Vs code
    Format on saveformat automatically after saving

  • 10.SourceTree
    Case recognition of open file: setting – editing configuration file: ignorecase = true [false: open case]

  • 11.Element-ui

    //verification
    this.$refs.examine.validateField("barCode");
    this.rules.barCode= [{ required: true, message: 'Please upload pictures' }]
    //Cancel validation
    this.$refs.examine.clearValidate('barCode');
    
    //input only numbers are allowed
     @change="value=value.replace(/[^\d]/g,'')"
    
    
  • 12.uni-app
    Return to the previous page and refresh

    let pages = getCurrentPages(); // Current page
    let beforePage = pages[pages.length - 2]; // previous page
    uni.navigateBack({
        success: function() {
            beforePage.onLoad(); // Execute the onLoad method on the previous page, which does not take effect. Find the operation by outputting beforePage
            
        }
    });
    
    

    Get status bar height

    Configuration information of mobile phone
    uni.getSystemInfoSync()
    Navigation bar height
    uni.getSystemInfoSync().statusBarHeight
    
    
  • 13. English

    handle //operation
    self //own
    secretary //secretary
    check //assessment
    increased //newly added
    decrease //reduce
    edit //edit
    push //Push
    Apush //Pushed
    issue //release
    Aissue //Published
    totalPoints //Total score
    decide //judge
    
    
  • 14.eCharts

    xAxis:
      name //Axis name
      boundaryGap //Left blank strategy on both sides of coordinate axis
      axisTick:{
        show:false, //Whether to display axis scale (small tip)
      }
      axisLable:{
        align:"center", //Text alignment under axis
        fontSize:10, //Text size
        interval:0, //Number of intervals when displaying data
      }
    yAxis:
      splitNumber:5, //Number of segments for the axis
      offset:-20, //Offset of the y-axis from the default position
      min:0, //Axis scale min
      max:100, //Axis scale Max
      [axisLable] //Same as xAxis
    grid:
      left:0, //Absolute value of distance from canvas component to the left
      top:10%, //Percentage of canvas component from top
      right:10,
      bottom:60,
    
    series:
      avoidLabelOverlap:false, //Enable prevent label overlap
      label:{
        show:true,
        posittion:"center",
        fontSize:18,
        fontWeight:"bold",
        padding:[-100,0,0,0],
        /*
          {a}: Series name
          {b}: Data name
          {c}: Data value
          {d}: percentage
          {@xxx}: The value of the dimension named 'xxx' in the data, for example, {@ product} represents the value of the dimension named 'product'
          {@[n]}: The value of dimension n in the data, such as {@[3]}, represents the value of dimension 3, counting from 0
        */
        formatter: '{b}: {d}', //Two forms of string template and callback function are supported: formatter: () = > {return '123'}
        color:"#ff3241",
      },
      itemStyle:{
        borderRadius:[15,15,0,0],//(clockwise, upper left, upper right, lower right, lower left)
        //Gradient effect. If the color fades when the mouse is placed in the first method, you can use the second method to change it to the same color
        //The first way, a color
        color:"#ff3241",
        //The second way, gradient
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          {offset: 0,color: "#fe9516"},{offset: 1, color: "#ffcb8c"},
        ]),
      },
      symbol:"base64", //Tagged graphics
      symbolSize: 18, //Size of tag
      symbolRotate: 6, //Rotation angle of the marker
      barWidth: 57, //Histogram column width
    
    
  • 15. Interview questions
    i18n: Vue I18n is Vue JS internationalization plug-in. Switch between Chinese and English

    The difference between call, apply and bind

    effect: call,apply,bind The function is to change the context of function execution this point
     difference:
      apply: 
        Two parameters are accepted. The first parameter is this The second parameter is the parameter accepted by the function, which is passed in the form of array
        change this After pointing, the original function will execute immediately, and this method is only temporarily changed this Point once
        When the first parameter is null,undefined The default point is window(In browser)
      call: 
        accept n The first parameter is this The second and the second are parameters
        change this After pointing, the original function will execute immediately, and this method is only temporarily changed this Point once
        When the first parameter is null,undefined The default point is window(In browser)
      bind: 
        bind Methods and call Very similar, so is the first parameter this The following is also a parameter list(However, this parameter list can be passed in multiple times)
        change this After pointing, it does not execute immediately, but returns a permanent change this Function pointing to
    
    

    Implement bind

    Function.prototype.myBind = function (context) {
        // Judge whether the calling object is a function
        if (typeof this !== "function") {
            throw new TypeError("Error");
        }
        // Get parameters
        const args = [...arguments].slice(1),
              fn = this;
        return function Fn() {
            // Different binding values are passed in according to the calling method
            return fn.apply(this instanceof Fn ? new fn(...arguments) : context, args.concat(...arguments)); 
        }
    }
    
  • 16.npm
    Install yarn

    npm install -g yarn
    ##Check whether the installation is successful
    yarn --version
    ##Install Taobao image for yarn source change
    yarn config set registry https://registry.npm.taobao.org
    ##yarn global install vite
    yarn create vite@2.7.2
    
    
  • vite-project
    Introduce normalize css

    //Installation dependency
    npm install normalize.css --save
    //main.ts introduction
    import 'normalize.css'
    

    Introducing eslint configuration

    npm install --save-dev eslint eslint-plugin-vue
    or 
    yarn add -D eslint eslint-plugin-vue
     Root directory creation.eslintrc.js
    
    
    • .eslintrc.js
      module.exports = {
        root: true,
        env: {
          node: true,
        },
        plugins: ["simple-import-sort"],
        extends: [
          "plugin:vue/vue3-recommended",
          "eslint:recommended",
          "@vue/typescript/recommended",
          "@vue/prettier",
          "@vue/prettier/@typescript-eslint",
        ],
        globals: {
          JSPlugin: true,
          vrv: true,
        },
        parserOptions: {
          ecmaVersion: 2020,
        },
        rules: {
          "no-console": "off",
          "no-debugger": "off",
          "no-unused-vars": "off",
          "@typescript-eslint/no-unused-vars": ["error"],
          "@typescript-eslint/no-var-requires": 0,
          // "@typescript-eslint/explicit-module-boundary-types": "off",
        },
      };
      
      

Keywords: Javascript Front-end html5

Added by busterbry on Tue, 18 Jan 2022 16:31:51 +0200