Using Vue instances (Global API s)

Overview

Vue.extend(options)                 // Create a Vue instance by inheriting an option object
Vue.nextTick([callback, context])   // Perform a deferred callback after the next DOM update cycle ends
Vue.set(target, key, value)         // Set the properties of the object. If it is a responsive object, it will trigger the view update
Vue.delete(target, key)             // Deleting the properties of an object, if it is a responsive object, will trigger a view update
Vue.directive(id, [definition])     // Register or get global directives
Vue.filter(id, [definition])        // Register or get global filter
Vue.component(id, [definition])     // Register or get global components
Vue.use(plugin)                     // Install the Vue plug-in
Vue.mixin(mixin)                    // Register a mixin object globally
Vue.compile(template)               // Compile the template string in the render function
Vue.version                         // Provide the version number of Vue currently in use

『 Vue.extend 』

In actual business development, we rarely use it because it returns the component constructor instead of the component instance we often write, so it can not be used directly through * * new Vue ({components: component name}) * *, which is better than the commonly used * * Vue Component} writing is more complicated
Usage scenario: Independent Component Development (Vue.extend + $mount_)_ For example, implement the notification pop-up component

// use
this.$notice(Notice, {
 title: 'Notification pop-up assembly',
 message: 'Prompt information',
 duration: 1000
}).show();
// create method
import Vue from "vue";
// Create an instance of it and mount it on the body
// Return component instance
function create(Component, props) {
  // 1. Vue.extend(options) mode
  const Ctor = Vue.extend(Component);
  const comp = new Ctor({propsData: props}); // Create component instance
  comp.$mount(); // If the host element is not specified, the real DOM is created, but the operation is not appended
  document.body.appendChild(comp.$el); // Mount the real DOM on the body
  comp.remove = () => {
    document.body.removeChild(comp.$el); // Remove DOM
    comp.$destroy(); // Destroy components
  };
  
  // 2. render mode
 	// const vm = new Vue({
  //    render(h) {
  //      //h is createElement, returns VNode, and is virtual DOM
  //      //You need to mount to become a real DOM
  //      return h(Component, { props });
  //    }
  //  }).$ mount(); //  In essence, vdom = > dom. If the host element is not specified, the real DOM will be created, but the operation will not be appended. If a host element is specified, it is overwritten directly

  //  document.body.appendChild(vm.$el); //  Get real DOM
  //  const comp = vm.$children[0]; //  Add destroy method to component instance

  //  comp. Remove = () = > {/ / delete
  //    document.body.removeChild(vm.$el);
  //    vm.$destroy();
  //  };
  return comp;
}
// Exposure adjustment
export default create;
// Notice.vue notification component
<template>
 <div class="box" v-if="isShow">
   <h3>{{title}}</h3>
   <p class="box-content">{{message}}</p>
 </div>
</template>

<script>
export default {
 props: {
   title: {
     type: String,
     default: ""
   },
   message: {
     type: String,
     default: ""
   },
   duration: {
     type: Number,
     default: 1000
   }
 },
 data() {
   return {
   	isShow: false
   };
 },
 methods: {
   show() {
     this.isShow = true;
     setTimeout(this.hide, this.duration);
   },
   hide() {
     this.isShow = false;
     this.remove();
   }
 }
};
</script>
<style>
.box {
 position: fixed;
 width: 100%;
 top: 16px;
 left: 0;
 text-align: center;
 pointer-events: none;
 background-color: #fff;
 border: grey 3px solid;
 box-sizing: border-box;
}
.box-content {
 width: 200px;
 margin: 10px auto;
 font-size: 14px; 
 padding: 8px 16px;
 background: #fff;
 border-radius: 3px;
 margin-bottom: 8px;
}
</style>
// Further encapsulate the plug-in to make it easy to create js
import Notice from '@/components/Notice.vue'
//...
export default {
 install(Vue) {
   Vue.prototype.$notice = function (options) {
   	 return create(Notice, options)
   }
 }
}

『 Vue.nextTick 』

Let's learn about it**_ nextTick _** Main application scenarios and reasons

  • In the Vue lifecycle**_ created() _** Hook function**_ DOM operations must be placed in Vue nextTick() _** In the callback function of

When the * * created() hook function is executed, the DOM is not actually rendered, and the DOM operation at this time is futile, so the DOM operation must be_ Put JS code into Vue nextTick() _** In the callback function of

  • When an operation needs to be performed after the data changes, and this operation needs to use the DOM structure that changes with the data changes, this operation should be put into**_ Vue.nextTick() _** In the callback function of
<div class="app">
  <div ref="msgDiv">{{msg}}</div>
  <div v-if="msg1">Message got outside $nextTick: {{msg1}}</div>
  <div v-if="msg2">Message got inside $nextTick: {{msg2}}</div>
  <div v-if="msg3">Message got outside $nextTick: {{msg3}}</div>
  <button @click="changeMsg">
    Change the Message
  </button>
</div>
new Vue({
  el: '.app',
  data: {
    msg: 'Hello Vue.',
    msg1: '',
    msg2: '',
    msg3: ''
  },
  methods: {
    changeMsg() {
      this.msg = "Hello world."
      this.msg1 = this.$refs.msgDiv.innerHTML
      /**
       * Vue.nextTick(options)
       * Used to delay the execution of a piece of code
       * Accept 2 parameters (callback function and context for executing callback function)
       * If no callback function is provided, the promise object is returned
       */
      this.$nextTick(() => {
        this.msg2 = this.$refs.msgDiv.innerHTML
      })
      this.msg3 = this.$refs.msgDiv.innerHTML
    }
  }
})

『 Vue.set 』

Vue.set(target, key, value)

  • **targe__t: * * data source to be changed (can be object or array)
  • **key: * * variable to modify
  • **value_ : _** Reassigned value

If a new property is added to the instance after the instance is created, it will not trigger the view update. When you pass in an ordinary JS object**_ Vue_** Instance as**_ data_** Option, Vue will traverse all the properties of this object and use object Defineproperty converts all these properties to getters / setters.
Limited by modern JS (and obsolete Object.observe), Vue cannot detect the addition or deletion of object properties. Because**_ Vue_** The property is executed when the instance is initialized_ getter/setter _ The conversion process, so the attribute must exist on the data object in order for Vue to convert it, so that it can be responsive.
Vue does not allow you to dynamically add new root level reactive properties on an instance that has been created. However, it can be used**_ Vue.set(object, key, value) _** Method to add a response property to a nested object.

『 Vue.delete 』

Vue.delete(target, key)

  • **target: * * data source to be changed (can be object or array)
  • **key: * * variable to delete

Delete the attributes of the object. If the object is responsive, ensure that the deletion can trigger the update of the view. This method is mainly used to avoid the restriction that Vue cannot detect the deletion of attributes

『 Vue.directive 』

**Vue _ Allows you to register custom directives for the underlying DOM_** Operate

// Vue.directive(id[, definition])
Vue.directive("focus", {
  /**
   * The following hook functions have the following parameters
   * el -> Instruction bound HTML elements that can be used to directly manipulate DOM
   * vnode -> Vue Compile generated virtual nodes
   * oldVnode -> The previous virtual nodes are only available in the update and componentUpdated hooks
   * binding -> An object that contains the following properties:
   * * name -> Instruction name, excluding v-prefix
   * * value -> The binding value of the instruction, for example, the value in v-my-directive="1 + 1" is 2
   * * oldValue -> The previous value of the instruction binding is only available in the update and componentUpdated hooks
   * * expression -> The string form of binding value. For example, the value of expression in v-my-directive="1 + 1" is "1 + 1"
   * * arg -> The parameter passed to the instruction. For example, the value of arg in v-my-directive:foo is "foo"
   * * modifiers -> Objects that contain modifiers, such as v-my-directive foo. The value of modifiers of bar is {foo: true, bar: true}
   */
  bind() {
    // The instruction is called only once when it is first bound to an element, and can be used to perform some initialization operations.
  },
  inserted(el) {
    // Called when the bound element is inserted into the parent node.
  },
  update() {
    // Called when the VNode of the component is updated, but may occur before its child VNode is updated.
  },
  componentUpdated() {
    // Called when the VNode of the component and its child vnodes are all updated.
  },
  unbind() {
    // When an instruction is unbound from an element, it will only be called once.
  }
})
// btnPermisstion.js
import store from '@/store/index'

export default {
  install (Vue) {
    Vue.directive('has', {
      bind (el, binding) {
        const permissionCode = binding.value
        const permissionList = store.getters.btnPermissions
        if (permissionList.indexOf(permissionCode) === -1) {
          Vue.prototype.$nextTick(() => {
            el.parentNode.removeChild(el)
          })
        }
      }
    })
  }
}

// main.js
import btnsPermission from './directive/btnPermisstion'
......

Vue.use(btnsPermission)

『 Vue.filter 』

**_ Vue can perform some common text formatting by defining filters, which can be used in mustache interpolation and v-bind expressions. When used, it can use the pipe symbol |_** It is added at the end of the expression, which is different from the calculation attribute in that it does not depend on the attribute in data

// filters.js
const numUnitConversion = value => {
  return value >= 10000 ? (value / 10000).toFixed(1) : value
}

const stubValue = value => {
  if (!value) {
    return '-'
  } else {
    return value
  }
}

export {
  stubValue,
  numUnitConversion
}
// main.js
import * as filters from './common/filters'

// Global filter settings
Object.keys(filters).forEach(key => {
  // Vue.filter(id[, definition])
  Vue.filter(key, filters[key])
})

Filter pipeline symbol directly * * |_** Connect the data to be filtered and define the configured filter function

<div class="info_tit info_last">
  <span>Total disk</span>
	<span><i class="color_6">{{ rectangleData.diskNum | stubValue }}</i> TB</span>
</div>

『 Vue.component 』

The behavior of global registration must occur before the root Vue instance (via * * new Vue * *) is created

<div id="app">        
    <div>#app</div>        
    <my-header></my-header>        
    <my-main></my-main>        
    <my-footer></my-footer>    
</div>    
<div id="root">        
    <div>#root</div>        
    <my-header></my-header>        
    <my-main></my-main>        
    <my-footer></my-footer>    
</div>

<script type="text/javascript" src="./vue.js"</script>
<script>    
    // Define components    
    const Header = {        
        template: '<header>Global header component</header>'    
    };    
    const Main = {
        template: '<main>Local body assembly</main>'    
    };   
    const Footer = {       
        template: '<footer>Global tail component</footer>'    
    };
    
    // Global registration component
    // Vue.component('component name '[, configuration object of component])
    Vue.component('my-header', Header);
    Vue.component('my-footer', Footer);
    
    // First instance    
    new Vue({        
        el: '#app',        
        // Local registration component - content        
        components: {            
            'my-main': Main        
        }    
     });  
    // Second instance    
    new Vue({        
        el: '#root',    
    })
</script>

Page run results

#app
 Global header component
 Local body assembly
 Global tail component
#root
 Global header component
 Global tail component

Console operation results

[Vue warn]: Unknown custom element: <my-main> - did you register the component correctly? For recursive components, make sure to provide the "name" option.

(found in <Root>)

An error will be reported: no local principal component is registered

『 Vue.use 』

**V__ue * * expand some global functions through plug-ins, * * Vue_ The plug-in will overwrite its install()_** Method, the first parameter of the method is**_ Vue _** Constructor, the second parameter is optional**_ option _** object
**_ V__ue _** First, judge whether the plug-in has been registered. Repeated registration is not allowed
If we pass in an object containing the install method, we will call the install method and pass the sorted array into the install method as a parameter
If we pass in a function, we will call the function directly and pass the sorted array as parameters
After that, add the plug-in to the added plug-in array to indicate that it has been registered, and finally return the Vue object

MyPlugin.install = function (Vue, options) {
  // Add a global method or property
  Vue.myGlobalMethod = function () {}
  // Add global resource
  Vue.directive("my-directive", {
    bind (el, binding, vnode, oldVnode) {}
  })
  // Injection assembly
  Vue.mixin({
    created: function () {}
  })
  // Add instance method
  Vue.prototype.$myMethod = function (methodOptions) {}
}
// Vue.use(plugin[, options])
Vue.use(MyPlugin, {someOption: true})

**_ When Vue router and other plug-ins detect that Vue is a global object, they will automatically call Vue Use(), if in CommonJS_** In a module environment, you need to explicitly call Vue use()

『 Vue.mixin 』

Use global**_ mixins will affect all Vue instances created later. If we don't want to mix these configuration options into every component instance, It's just an individual component. It's best not to use it_ mixin_**, It may affect the performance of our components.

// *.vue
<template>
  <div id="box">
    <nav-header ref="navHeader" title="AI-fisher" :styleObject="navHeaderStyle" :shareParams="shareParams"></nav-header>
    ......
    <cube-scroll :options="options" :listenScroll="true" @scroll="scrolling" ref="scroll">
      ......
    </cube-scroll>
		......
  </div>
</template>
// main.js
Vue.mixin({
  data () {
    return {
      navHeaderStyle: {
        opacity: 0
      }
    }
  },
  methods: {
    scrolling(a) {
      let num = ~Math.floor(a.y) > 0 ? ~Math.floor(a.y) > 128 ? 128 : ~Math.floor(a.y) : 0
      this.navHeaderStyle.opacity = num / 128
    }
  }
})

『 Vue.compile』

In**_ render_** Function to compile the template string. Valid only when built independently

// Vue.compile(template)
const res = Vue.compile('<div><span>{{ msg }}</span></div>')
 
new Vue({
  data: {
    msg: 'hello'
  },
  render: res.render,
  staticRenderFns: res.staticRenderFns
})

『 Vue.version  』

Get currently used**_ Vue_** Version number. When we look for some dependent packages installed, we need to know the supported Vue version, so this method will be used at this time. Its principle is to read**_ package.json _** Version field in

Keywords: Javascript Front-end Vue.js api

Added by jefrat72 on Thu, 20 Jan 2022 11:33:10 +0200