[Vue] API on Vue

Time:2021-10-22

API on Vue

  1. Vue.extend
  2. Vue.component
  3. Vue.use
  4. Vue.set
  5. Vue.delete
  6. Vue.directive
  7. Vue.filter
  8. Vue.nextTick
  9. Vue.mixin
  10. Vue.compile
  11. Vue.observable
  12. Vue.version

1 Vue.extend({options})

Create one through VueSubclass, the parameter is aComponent optionsofobject
The data option must be a function

During initialization, it will be judged that data isfunctionstillobject
function: execute this function to return a new object
objectDirect useThis object is public when instantiating this subclass,Global pollution

//Create subclass
const myVue = Vue.extend({
    Template: '< p > the price of the shirt is {{price}} < / P >',
    data() {
        return {
            Price: "nine pounds and fifteen pence"
        }
    },
})
//Instantiate subclasses and mount
const myVm1 = new myVue().$mount("#root1")
const myVm2 = new myVue({ el: "#root2" })

//Results
<p>The price of the shirt is nine pounds and fifteen pence</p>
<p>The price of the shirt is nine pounds and fifteen pence</p>

Dynamic rendering component, which can be called like a function

2 Vue.component(id , [definition])

Define components, a component is a reusable Vue instance that can be used as a custom element
The definition can be Vue. Extend (options), or it can directly make an options object – or it will execute Vue. Extend ()

//Define a component
Vue.component('Child1', {
    Template: ` < p > the price of the shirt is {price}} < / P > `,
    data() {
        return {
            Price: "nine pounds and fifteen pence",
        }
    },
})
new Vue().$mount('#root1')

//Define subclasses
const myVue = Vue.extend({
    Template: ` < p > My name is {{name}} < / P > `,
    data() {
        return {
            Name: "Han Meimei"
        }
    },
})
Vue.component('Child2', myVue)
new Vue().$mount('#root2')
<div id="root1">
    <Child1></Child1>
</div>
<div id="root2">
    <Child2></Child2>
</div>

The above two methods can customize a component

3 Vue.use(plugin)

Install plug-insGenerally, you need to install a package before using it in VueintroducethenVue.useIt can only be used after, vue.use willcallIn this moduleinstallmode
Use the use method to define components and simulate the installation process of plug-ins

//Mycomponent.vue file
<template>
  < div > loading... < / div >
</template>

//Create index.js for encapsulation
import MyComponent from './MyComponent.vue'

const My = {
    install(Vue) {
        Vue.component('My', MyComponent)
    }
}
export default My

//Install in main.js
import My from './components/index'
Vue.use(My)

//Reference in other components
<My />

Use is actually calling install and then returning

4 Vue.set(target,key,value) Vue.delete(target,key)

Add or modifyProperty of the responsive object,Target cannot be a Vue instance or the root data object of a Vue instance

//Vue instance
<template>
  <div class="main">
    <input type="text" v-model="std.name" />
    < input type = "button" value = "modify" @ Click = "modify" / >
    < input type = "button" value = "delete" @ Click = "delete" / >
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      std: {
        Name: "Zhang San",
      },
    };
  },
  methods: {
    Modify() {
      This. $set (this. STD, "name", "Li Si");
    },
    Delete() {
      this.$delete(this.std, "name");
    },
  },
};
</script>

5 Vue.filter(id,[definition])

Register or get globalfilter

//Global registration in main.js
Vue.filter('upperCase', value => {
  return value.toUpperCase()
})
//Used in components
<template>
  <div class="main">
    <span>{{ name | upperCase }}</span>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      name: "bob",
    };
  },
};
</script>

Filter toPipe symbolAs the first parameter of the filter before the pipe character, additional parameters can be added
You can add another receive filterReturn value of the previous filter, still separated by pipe characters

6 Vue.mixin(mixin)

Global blending
You can inject custom behavior on all Vue instances
Minxin is aobject, you can define related properties and methods

//Mixin.js file definition blending
export const mixin = {
    mounted() {
        Console.log (this. _uid + "Mount completed")
    },
}
//Main.js price asking registration
import { mixin } from './mixin'
Vue.mixin(mixin)

7 Vue.directive(id,[definition])

Register or obtainGlobal instruction

//Main.js file customization instruction
Vue.directive('focus', {
  inserted(el, binding) {
    el.focus()
    el.value = binding.value;
  },
})
//Use in components
<template>
  <div class="main">
    <input type="text" v-focus="tip" />
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      Tip: "please enter your name",
    };
  },
};
</script>
  • When definingidDo not add beforev-, add when using
  • definitionIt’s aobject, including hook function

7.1 hook function of custom instruction

bindFirst instruction:bindingCalled when an element is found, only once

inserted: elements of binding instructionsinsertCalled when the parent node

updateVnode of the component:to updateIt may occur before its child vnode is updated

componentUpdated: the vnode of the component where the instruction is located and its child vnodesAfter all updatescall

unbind: instructions and elementsUnboundCalled only once

7.2 hook function parameters

  • el: bound element, real DOM
  • binding: an object with the following properties:

    • name: instruction name
    • value: instruction binding value=Value after
    • oldValue: Previous binding value, only into updateUsed in two hooks
    • expression: instruction expression in string form
    • arg: parameters passed to the instruction:Value after
    • modifiers: objects containing modifiers
  • vnode: virtual nodes generated by Vue compilation
  • oldVnode: last virtual node, only into updateUsed in two hooks

8 Vue.nextTick([callback,context])

The next DOM update cycle endsA deferred callback is then performed
Use this method immediately after modifying the data to get the updated dom
No callback returns a promise

<template>
  <div>
    <ul ref="ulEl">
      <li v-for="item in list" :key="item">{{ item }}</li>
    </ul>
    < input type = "button" value = "add" @ Click = "add" / >
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      list: ["0", "1"],
    };
  },
  methods: {
    async add() {
      //Batch add data
      this.list.push(Math.random());
      this.list.push(Math.random());

      //Get element
      const ulElem = this.$refs.ulEl;

      console.log(ulElem.childNodes.length);//2
      await this.$nextTick();
      console.log(ulElem.childNodes.length);//4
    },
  },
};
</script>

The latest DOM is not obtained before nexttick (). Nexttick () will be called only after the complete update is completed, and then the latest DOM can be obtained

9 Vue.compile(template)

Add a template stringcompileInto render function,Use only in full version

Let res = Vue. Compile ('< p > shirt plus {{price}} < / P >')
new Vue({
    data() {
        return {
            Price: "nine pounds and fifteen pence",
        }
    },
    render: res.render
}).$mount('#root1')

Using the render function, you don’t have to add template

10 Vue.observable(object)

Let an objectResponsive, you can replace vuex to implement state management in smaller projects

//Store.js state management
import Vue from 'vue'

export let store = {
    state: Vue.observable({ count: 0 }),
    mutations: {
        setCount(count) {
            store.state.count = count;
        }
    }
}
//Sub component display data
<template>
  <span>{{"count of subcomponent:" + count}}</span>
</template>

<script>
import { store } from "../store";
export default {
  computed: {
    count() {
      return store.state.count;
    },
  },
};
</script>
//Parent component modify and display data
<template>
  <div>
    <span>{{"count in store:" + count}}</span>
    <br />
    <input type="button" value="+" @click="setCount(count + 1)" />
    <input type="button" value="-" @click="setCount(count - 1)" />
    <br />
    <Child />
  </div>
</template>

<script>
import { store } from "./store";
import Child from "./components/Child.vue";
export default {
  name: "App",
  components: {
    Child,
  },
  computed: {
    count() {
      return store.state.count;
    },
  },
  methods: {
    setCount: store.mutations.setCount,
  },
};
</script>

When the parent component is modified, the child component will respond at the same time

11 Vue.version

Vue installation version number

import Vue from 'vue'
console.log(Vue.version);//2.6.14

other

Print out the Vue constructor and you can see that it has several properties

  • Vue.options
  • Vue.util
  • Vue.config

These will be separately exemplified later and will not be described here