0.1. How to use and pay attention to mixins in vue

Usage scenarios
When you have two components that are very similar, their function is very similar, but they are locally slightly different. A Mixins in a Vue is basically a piece of defined logic that is stored by the Vue in a specified way and can be used repeatedly to add functionality to Vue instances and components. As a result, Vue mixins can be shared across multiple Vue components without repeating code blocks.Copy the code
Vuex, mixins, common components
  • Vuex: Used for state management. Variables defined in vuEX can be used and modified in each component. After changing the value of a variable in any component, the value of a variable in other components will also be modified.
  • Mixins: Common variables can be defined and used in each component. Once introduced into the component, the variables are independent of each other and value changes do not affect each other in the component.
  • Component: Introducing a component in the parent is equivalent to giving the parent an independent space for the child component to use, and then passing values according to the props, but essentially the two are relatively independent.
  • Mixins: merge the objects and methods of the component after introducing the component, which extends the objects and methods of the parent component, and can be understood as forming a new component.
Merging rules
- Data objects are internally recursively merged and take precedence over component data in case of conflicts. - The same name hook functions (e.g. Created, Mounted) will be merged into an array and will therefore be called. In addition, hooks mixed in with objects are called before the component's own hooks. - The options that are values for objects, such as Methods, Components, and directives, will be combined into the same object. When two object key names conflict, the component object's key-value pair is taken.Copy the code
Local mixins
//toggle.js
export const toggle = {
  data() {
    return {
      "show": false}},methods: {
    changeState() {
      this.show = !this.show; }}};Copy the code
<template>
  <div>
    <div v-show="show">
      <p>Prompt box</p>
    </div>
    <button @click="changeState">click</button>
  </div>
</template>

<script>
import {toggle} from './mixins/toggle'

export default {
  mixins: [toggle]
}
</script>
Copy the code
Local mixins
<script>
import vue from 'vue'

vue.mixin({
  created() {
    // Custom options
    const myOption = this.$options.myOption;
    if (myOption) {
      // Print if myOption has a value
      console.log(myOption); }}})export default {
  myOption: "hello world!"
}
</script>
Copy the code

Note: Be careful with global mixin, as it affects each individually created Vue instance (including third-party components). In most cases, this should only apply to custom options, as in the example above. It is recommended to publish it as a plug-in to avoid repeated application mixing.

0.2. Differences between VUex storage and local storage

  1. The difference between:Vuex stores status, stored in memory, localstorage (localstorage) is the interface provided by the browser, let you save is the interface, in the form of a file stored locally, permanent storage; Sessionstorage, temporary storage. LocalStorage and sessionStorage can only store string types, and for complex objects can be handled using Stringify and Parse for JSON objects provided by ECMAScript

Vuex is used for state management, managing communication between different components on a page

Since most of the APP is composed of single-page components, I don't have the problem of communicating between different components on the same page. Vuex, as a library that implements flux idea, mainly aims to achieve the following functions: - Data communication between components - centralized data management in the way of one-way data flowCopy the code
  1. Application Scenarios:Vuex is used to transfer values between components, while localStorage and sessionStorage are used to transfer values between different pages.
  2. Permanent:Vuex is lost when the page is refreshed, sessionStorage is cleared after the page is closed, localstorage is not.

Note: Many students think that using localStorage can replace VUEX. It is possible for unchanging data. However, when two components share a data source (object or array), if one component changes the data source and expects the other component to respond to the change, localstorage, Sessionstorage cannot do this because of difference 1.

ES6 tutorial async functions

Characteristics of async functions

  • Strong semantic:Async means that there is an asynchronous operation in a function, and await means that the following expression needs to wait for the result.
  • The await inside can only be used in async functions
  • The statements following await can be promise objects, numbers, strings, etc
  • The async function returns a Promsie object
  • When the Promise object after the await statement becomes reject, the whole async function breaks and subsequent programs do not continue

Try /catch/finally statements are used to handle possible error messages in your code. Errors can be syntax errors, usually coding errors or typos made by programmers. It could also be a spelling mistake or a missing feature in the language (possibly due to browser differences). The try statement allows us to define blocks of code that are tested for errors at execution time. The catch statement allows us to define the block of code to execute when an error occurs in the try block. A finally statement is executed after a try and catch with or without exceptions. Note: Both catch and finally statements are optional, but you must use at least one when using try statements. Tip: JavaScript stops execution and generates an error message when an error occurs. Use a throw statement to create a custom message that throws an exception. If you use throw with a try and catch, you can control the error messages your program outputs.

// promise.js
// Since reading multiple files is usually handled as an asynchronous, so as not to block the program, wrap the FS as a Promise object and return the data output below. In this example, the TXT file can write its own data
const fs = require("fs");
const read = function(fileName){
    return new Promise((resolve,reject) = >{
        fs.readFile(fileName,(err,data) = >{
            if (err) {
                reject(err);
            } else{ resolve(data); }}); }); }; read('1.txt').then(res= >{
    console.log(res.toString());
    return read('2.txt');  // Return the new data, then print
}).then(res= > {
    console.log(res.toString());
    return read('3.txt');
}).then(res= > {
    console.log(res.toString());
});
Copy the code
// generator.js
// This way the amount of code is much higher, and the Promise way is very similar, but is to read the file information outside, in the following sequence of manual calls, particularly troublesome
const fs = require("fs");
const read = function(fileName){
    return new Promise((resolve,reject) = >{
        fs.readFile(fileName,(err,data) = >{
            if (err) {
                reject(err);
            } else{ resolve(data); }}); }); };function * show(){
    yield read('1.txt');
    yield read('2.txt');
    yield read('3.txt');
}
const s = show();
s.next().value.then(res= > {
    console.log(res.toString());
    return s.next().value;
}).then(res= > {
    console.log(res.toString());
    return s.next().value;
}).then(res= > {
    console.log(res.toString());
});
Copy the code
// async.js
// This function is similar to generator functions. As can be seen from examples, async functions are marked with an async before function, which means an async function is used with an "await" function
const fs = require("fs");
const read = function(fileName){
    return new Promise((resolve,reject) = >{
        fs.readFile(fileName,(err,data) = >{
            if (err) {
                reject(err);
            } else{ resolve(data); }}); }); };async function readByAsync(){
  let a1;
  let a2;
  let a3;
  try{
      a1 = await read('1.txt');
      a2 = await read('2.txt');
      a3 = await read('3.txt');
  }catch(e){
      //TODO handle the exception
  }
  console.log(a1.toString());
  console.log(a2.toString());
  console.log(a3.toString());
}
readByAsync();
Copy the code

4 NPM install -s -d -g

NPM install module_name -s is NPM install module_name --save write to dependencies NPM install module_name -d is NPM install Module_name --save-dev write devDependencies NPM install module_name -g Global install NPM install module_name local install /node_modules) dependencies are only used in the development environment, not in the production environmentCopy the code

FastClick and Element conflict on IOS

With fastclick, label>input[type=radio]+span (EL-radio), click text can not select the radio

/* Solution: add style */
label > * { pointer-events: none; }
Copy the code

Fastclick.js causes input and Textarea to be hard to focus

FastClick.prototype.focus = function(targetElement) {
var length;
var deviceIsWindowsPhone = navigator.userAgent.indexOf("Windows Phone") > =0;
var deviceIsIOS = /iP(ad|hone|od)/.test(navigator.userAgent) && ! deviceIsWindowsPhone;// compatibility handling: in iOS7, some elements (such as date, datetime, month, etc.) will show TypeError in setSelectionRange
The setSelectionRange method is used to exclude elements that do not have the selectionStart and selectionEnd integer attributes
if (deviceIsIOS && targetElement.setSelectionRange && targetElement.type.indexOf('date')! = =0&& targetElement.type ! = ='time'&& targetElement.type ! = ='month'&& targetElement.type ! = ='email') {
    length = targetElement.value.length;
    targetElement.setSelectionRange(length, length); // Fix bug ios 11.3 doesn't pop keyboard, add focus code to force focus pop keyboard
    targetElement.focus();
} else{ targetElement.focus(); }}Copy the code

After upgrading to ios11.3, the input box click became insensitive, and the second click on the input box on the page required a long press to properly invoke keyboard input

FastClick.prototype.focus = function(targetElement) {
targetElement.focus();
};
Copy the code

Fixed an issue with the Element UI Select drop-down box requiring two clicks on ios mobile

.el-scrollbar{>.el-scrollbar__bar {
    opacity: 1 ! important; }}Copy the code

6, mobile terminal sliding is not smooth bug

-webkit-overflow-scrolling: touch;
Copy the code

7, compatible with Promise

// Something like this
if(!window.Promise) {
document.writeln('< script SRC = "https://as.alipayobjects.com/g/component/es6-promise/3.2.2/es6-promise.min.js" "+'>'+'<'+'/'+'script>');
}
Copy the code

8, mobile terminal 300ms delay

<meta name="viewport" content="width=device-width">
Copy the code
html {
touch-action: manipulation;
}
Copy the code
// fastclick
Copy the code

9. Ios wechat keyboard retraction may lead to input dislocation

$("input").on('blur'.function() {
window.scrollTo(0.0);
});
Copy the code

10. Remove the clear flag that comes with input Search

input[type=search]::-webkit-search-cancel-button{
-webkit-appearance: none;
}
Copy the code

11. Display “search” in the lower right corner of the keyboard on the mobile terminal

<form onsubmit="return false;" action="javascript:return true">
<input type="search" autocomplete="off" placeholder="Search terms" />
</form>
Copy the code

12. Use of bodyScrollLock

/ / lock body
bodyScrollLock.disableBodyScroll(document.querySelector('.poi-history-content'));
/ / the liberation of the body
bodyScrollLock.enableBodyScroll(document.querySelector('.poi-history-content'));
// Clear the lock
bodyScrollLock.clearAllBodyScrollLocks()
Copy the code

13. Solve the problem that H5 page numbers in iOS pages are recognized as phone numbers

<meta name = "format-detection" content = "telephone=no">
Copy the code

Rem-generated location bug was used on ios when using cSS3 Animation KeyFrame

// Use setTimeout(fn,0) to execute the loaded animation class at the end of the thread, so that the animation behaves normally.

setTimeout(() = >{$("#id").addClass("animation")},0)
Copy the code

14. Roll back the refresh page

window.addEventListener('pageshow'.function (event) {
if (event.persisted || window.performance && window.performance.navigation.type == 2) {
location.reload()
}
})
Copy the code

15. Fixed an issue where ios textarea could not be typed

$('textarea').attr('contenteditable'.trueThe $()'textarea').css('-webkit-user-select'.'auto')
Copy the code

16. To allow events to pass through the mask layer, you can set CSS properties on the mask layer

pointer-events: none;
Copy the code

Vue CLI3 uses AXIOS to load local files

// the file is placed under public
'/ /public/... File '
axios.get('/public/test.json').then(res= >{})
Copy the code

Vue CLI3 memory is not enough

// step1 install dependencies
yarn add increase-memory-limit -D
yarn add cross-env -D 
// The second step is configured in the package.json script
"fix-memory-limit": "cross-env LIMIT=4096 increase-memory-limit".Copy the code

19. The vUE project failed to send requests to the background when closing the browser

    // The browser window closes
    window.addEventListener("beforeunload".e= > {
      console.log(e);
      // A confirmation dialog box is displayed, prolonging the shutdown period. Otherwise, the request cannot be sent successfully and cannot be received
      // Compatible with IE8 and Firefox 4 prior versions
      e = e || window.event;
      if (e) {
        e.returnValue = "Off tip";
      }
      In IE, this event is triggered when you just close the window.
      // 2, Google, Firefox, etc. will also work in F12 debug mode
      // 3, Google, Firefox, QQ and other browsers are optimized, requiring users to have any operation on the page will appear prompt! (pit).
      mdLeaveReport();
      // Chrome, Safari, Firefox 4+, Opera 12+ , IE 9+
      return "Off tip";
    });
  }
Copy the code