What are the commonly used APIs in Vue?

青灯夜游
Release: 2022-03-07 14:12:38
Original
2610 people have browsed it

Vue’s APIs include: 1. nextTick; 2. mixin; 3. “$forceUpdate”; 4. set and delete; 5. filter; 6. directive; 7. “$root”; 8. “ $el"; 9. "$data"; 10. "$props", etc.

What are the commonly used APIs in Vue?

The operating environment of this tutorial: windows7 system, vue2.9.6 version, DELL G3 computer.

nextTick


Function: Add a delayed callback after the next Dom update cycle ends. After modifying the data, you can get the updated Dom.
Usage:

Vue.nextTick( [callback, context] )
vm.$nextTick( [callback] )
// 用法2
// 作为一个 Promise 使用 (2.1.0 起新增)
Vue.nextTick()
  .then(function () {
    // DOM 更新了
  })
Copy after login

Description:

    ##callback: delayed callback function
  • context: optional object
ps: New since 2.1.0: If no callback is provided and in an environment that supports Promise, a Promise is returned. Please note that Vue does not come with Promise polyfills, so if your target browser does not natively support Promise (IE: why are you looking at me), you have to provide the polyfill yourself.

Extension: Regarding the execution mechanism and usage scenarios of nextTick, we must also master the similar requestAnimationFrame() and process.nextTick(). The former is the browser’s own monitor (before the next redraw) Execution), the latter is executed at the next event polling time point in the node environment.

mixin


Function: Register a mixin that affects every Vue instance created after registration. Plug-in authors can use mixins to inject custom behaviors into components.
Usage:

// 为自定义的选项 'myOption' 注入一个处理器。
Vue.mixin({
  created: function () {
    var myOption = this.$options.myOption
    if (myOption) {
      console.log(myOption)
    }
  }
})

new Vue({
  myOption: 'hello!'
})
// => "hello!"
Copy after login

Description:

##object: a vm attribute or method
  • ps: Please use global mixins with caution, as it will affect each individually created Vue instance (including third-party components). In most cases, this should only be applied to custom options, like the example above. It is recommended to publish it as a plugin to avoid repeated application mixins.

$forceUpdate


Function:

Force the Vue instance to re-render. Usage:

vm.$forceUpdate()
Copy after login

Description:

Note that it only affects the instance itself and the subcomponents inserted into the slot content, not all subcomponents. set, delete


Function:

Set and delete the properties of responsive data, and trigger view updates at the same time. Usage:

// 用法1
Vue.set( target, key, value )
Vue.delete( target, key )
// 用法2
vm.$set( target, key, value )
vm.$delete( target, key )
Copy after login

Description:

target: target object
  • key: to be added Property name
  • value: The property value to be added
  • ps: Main usage scenarios, which can avoid the limitation that Vue cannot detect property deletion

filter


Function:

Used for some common text formatting and some standard data mapping. Usage:

<!-- 在双花括号中 -->
{{ message | capitalize }}

<!-- 在 `v-bind` 中 -->
<div v-bind:id="rawId | formatId"></div>
Copy after login
// 注册
filters: {
  capitalize: function (value) {
    if (!value) return &#39;&#39;
    value = value.toString()
    return value.charAt(0).toUpperCase() + value.slice(1)
  }
}
Copy after login
// 全局注册
Vue.filter(&#39;capitalize&#39;, function (value) {
  if (!value) return &#39;&#39;
  value = value.toString()
  return value.charAt(0).toUpperCase() + value.slice(1)
})

new Vue({
  // ...
})
Copy after login

Description:

The filter function always receives the value of the expression (the value of the previous operation chain result) as the first argument.
  • Filters should be added at the end of JavaScript expressions, indicated by the "pipe" symbol.
ps: The filter can accept multiple parameters, such as {{ message | filterA('arg1', arg2) }}. Here, filterA is defined as a filter that receives three parameters. device function. The value of message is used as the first parameter, the ordinary string 'arg1' is used as the second parameter, and the value of the expression arg2 is used as the third parameter.

directive


Function:

Used to register custom instructions. Usage:

<!-- 当页面加载时,该元素将获得焦点 --> 
<input v-focus>
Copy after login
// 注册一个全局自定义指令 `v-focus`
Vue.directive(&#39;focus&#39;, {
  // 当被绑定的元素插入到 DOM 中时……
  inserted: function (el) {
    // 聚焦元素
    el.focus()
  }
})
Copy after login
// 注册局部指令,组件中也接受一个 directives 的选项
directives: {
  focus: {
    // 指令的定义
    inserted: function (el) {
      el.focus()
    }
  }
}
Copy after login

Instructions:

inserted is just one of the interpolation functions of the registration command, and the complete registration attributes are also Can include:
  • bind: only called once, called when the instruction is bound to the element for the first time. One-time initialization settings can be performed here.
    • inserted: Called when the bound element is inserted into the parent node (only the parent node is guaranteed to exist, but not necessarily inserted into the document).
    • update: Called when the VNode of the component is updated, but may occur before its child VNode is updated. The directive's value may or may not have changed, but unnecessary template updates can be ignored by comparing the values ​​before and after the update.
    • componentUpdated: Called after all the VNode of the component where the instruction is located and its sub-VNodes have been updated.
    • unbind: Called only once, when the instruction is unbound from the element.
    Vue.directive(&#39;my-directive&#39;, {
      bind: function () {},
      inserted: function () {},
      update: function () {},
      componentUpdated: function () {},
      unbind: function () {}
    })
    Copy after login
  • v-model syntax sugar


v-model is often used for two-way binding of data on form elements, such as . In addition to native elements, it can also be used in custom components.

v-model is a syntactic sugar that can be decomposed into props: value and events: input. That is to say, the component must provide a prop named value and a custom event named input. If these two conditions are met, the user can use v-model on the custom component. For example, the following example implements a number selector:

<template>
  <div>
    <button @click="increase(-1)">减 1</button>
    <span >{{ currentValue }}</span>
    <button @click="increase(1)">加 1</button>
  </div>
</template>
<script>
  export default {
    name: &#39;InputNumber&#39;,
    props: {
      value: {
        type: Number
      }
    },
    data () {
      return {
        currentValue: this.value
      }
    },
    watch: {
      value (val) {
        this.currentValue = val;
      }
    },
    methods: {
      increase (val) {
        this.currentValue += val;
        this.$emit(&#39;input&#39;, this.currentValue);
      }
    }
  }
</script>
Copy after login

props 一般不能在组件内修改,它是通过父级修改的,因此实现 v-model 一般都会有一个 currentValue 的内部 data,初始时从 value 获取一次值,当 value 修改时,也通过 watch 监听到及时更新;组件不会修改 value 的值,而是修改 currentValue,同时将修改的值通过自定义事件 input 派发给父组件,父组件接收到后,由父组件修改 value。所以,上面的数字选择器组件可以有下面两种使用方式:

<template>
  <InputNumber v-model="value" />
</template>
<script>
  import InputNumber from &#39;../components/input-number/input-number.vue&#39;;

  export default {
    components: { InputNumber },
    data () {
      return {
        value: 1
      }
    }
  }
</script>
Copy after login

或:

<template>
  <InputNumber :value="value" @input="handleChange" />
</template>
<script>
  import InputNumber from &#39;../components/input-number/input-number.vue&#39;;

  export default {
    components: { InputNumber },
    data () {
      return {
        value: 1
      }
    },
    methods: {
      handleChange (val) {
        this.value = val;
      }
    }
  }
</script>
Copy after login

如果你不想用 value 和 input 这两个名字,从 Vue.js 2.2.0 版本开始,提供了一个 model 的选项,可以指定它们的名字,所以数字选择器组件也可以这样写:

<template>
  <div>
    <button @click="increase(-1)">减 1</button>
    <span >{{ currentValue }}</span>
    <button @click="increase(1)">加 1</button>
  </div>
</template>
<script>
  export default {
    name: &#39;InputNumber&#39;,
    props: {
      number: {
        type: Number
      }
    },
    model: {
      prop: &#39;number&#39;,
      event: &#39;change&#39;
    },
    data () {
      return {
        currentValue: this.number
      }
    },
    watch: {
      value (val) {
        this.currentValue = val;
      }
    },
    methods: {
      increase (val) {
        this.currentValue += val;
        this.$emit(&#39;number&#39;, this.currentValue);
      }
    }
  }
</script>
Copy after login

在 model 选项里,就可以指定 prop 和 event 的名字了,而不一定非要用 value 和 input,因为这两个名字在一些原生表单元素里,有其它用处。

.sync 修饰符

如果你使用过 Vue.js 1.x,一定对 .sync 不陌生。在 1.x 里,可以使用 .sync 双向绑定数据,也就是父组件或子组件都能修改这个数据,是双向响应的。在 Vue.js 2.x 里废弃了这种用法,目的是尽可能将父子组件解耦,避免子组件无意中修改了父组件的状态。

不过在 Vue.js 2.3.0 版本,又增加了 .sync 修饰符,但它的用法与 1.x 的不完全相同。2.x 的 .sync 不是真正的双向绑定,而是一个语法糖,修改数据还是在父组件完成的,并非在子组件。

仍然是数字选择器的示例,这次不用 v-model,而是用 .sync,可以这样改写:

<template>
  <div>
    <button @click="increase(-1)">减 1</button>
    <span >{{ value }}</span>
    <button @click="increase(1)">加 1</button>
  </div>
</template>
<script>
  export default {
    name: &#39;InputNumber&#39;,
    props: {
      value: {
        type: Number
      }
    },
    methods: {
      increase (val) {
        this.$emit(&#39;update:value&#39;, this.value + val);
      }
    }
  }
</script>
Copy after login

用例:

<template>
  <InputNumber :value.sync="value" />
</template>
<script>
  import InputNumber from &#39;../components/input-number/input-number.vue&#39;;

  export default {
    components: { InputNumber },
    data () {
      return {
        value: 1
      }
    }
  }
</script>
Copy after login

看起来要比 v-model 的实现简单多,实现的效果是一样的。v-model 在一个组件中只能有一个,但 .sync 可以设置很多个。.sync 虽好,但也有限制,比如:

  • 不能和表达式一起使用(如 v-bind:title.sync="doc.title + '!'" 是无效的);

  • 不能用在字面量对象上(如 v-bind.sync="{ title: doc.title }" 是无法正常工作的)。

其它简单的常用属性和方法

// console.log(vm.$root); 
vm.$root    //实例对象

vm.$el  //根元素(真实的DOM元素)
// console.log(vm.$el);

vm.$el.innerHTML    //得到根元素(真实的DOM元素)中的内容
// console.log(vm.$el.innerHTML);

vm.$data    //实例下的data对象
// console.log(vm.$data);

vm.$options     //实例下的挂载项
// console.log(vm.$options);

vm.$props   //组件之间通信的数据
// console.log(vm.$props);

vm.$parent      //在组件中,指父元素
// console.log(vm.$parent);

vm.$children    //在组件中,指子代元素
// console.log(vm.$children);

vm.$attrs   //用来获取父组件传递过来的所有属性
// console.log(vm.$attrs);

vm.$listeners   //用来获取父组件传递过来的所有方法
// console.log(vm.$listeners);

vm.$slots   //组件中的插槽
// console.log(vm.$slots);

vm.$scopedSlots     //用来访问作用域插槽
// console.log(vm.$scopedSlots);

vm.$refs    //用来定位DOM元素(使用ref进行追踪)
// console.log(vm.$refs);

vm.$watch   //用于监听数据(在vue文件中使用后会自动销毁)
// console.log(vm.$watch);

vm.$emit    //用于派发事件(常用于数据通信)
// console.log(vm.$emit);

vm.$on  //用于监听事件的派发
// console.log(vm.$on);

vm.$once    //只监听事件一次(之后不监听)
// console.log(vm.$once);

//生命周期
beforeCreate() {
}
created() {
}
beforeMount() {
}
mounted() {
}
beforeUpdate() {
}
updated() {
}
beforeDestroy() {
}
destroyed() {
}
Copy after login

(学习视频分享:vuejs教程web前端

The above is the detailed content of What are the commonly used APIs in Vue?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template