search
HomeWeb Front-endJS TutorialVue2.0 custom directives and instance properties and methods

Vue2.0 custom directives and instance properties and methods

Jul 13, 2018 pm 05:27 PM
html5javascriptvue.js

This article mainly introduces the properties and methods of Vue2.0 custom instructions and instances. It has a certain reference value. Now I share it with you. Friends in need can refer to it.

1. Self- Definition instructions

Vue custom instructions have two methods of global registration and local registration, just like components. Let’s first look at how to register global instructions. Register global instructions through Vue.directive(id, [definition]). The second parameter can be object data or a directive function.

Note: When using the command, you must add the prefix v- before the named name, that is, v-command name

1. Hook function

A command definition object can provide the following Hook functions (all optional):

  • bind: only called once, when the instruction is bound to an 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 template where the bound element is located is updated, but may occur before its child VNode is updated.

  • componentUpdated: Called when the template where the bound element is located completes an update cycle.

  • unbind: Called only once, when the instruction is unbound from the element.

2. Hook function parameters

The command hook function will be passed in the following parameters:

el: The element bound by the command, which can be used To directly operate the DOM

binding: an object containing the following attributes:

name:指令名,不包括 v- 前缀。
value:指令的绑定值,例如:v-my-directive="1 + 1" 中,绑定值为 2。
expression:字符串形式的指令表达式。例如 v-my-directive="1 + 1" 中,表达式为 "1 + 1"
arg:传给指令的参数,可选。例如 v-my-directive:foo 中,参数为 "foo"。
modifiers:一个包含修饰符的对象。例如:v-my-directive.foo.bar 中,修饰符对象为 { foo: true, bar: true }
<p>
   </p><h3 id="msg">{{msg}}</h3>

...
// 钩子函数的参数
Vue.directive('world', {
  bind(el, binding) {
    console.log(el);//指令所绑定的元素,DOM对象
    el.style.color = 'yellow';
    console.log(binding); 
  }
});
Get the following results:

Vue2.0 custom directives and instance properties and methods

3. Function abbreviation

In many cases, you may want to trigger the same behavior during bind and update without caring about other hooks

//传入一个简单的函数,bind和update时调用
 Vue.directive('wbs',function(){
   alert('wbs17022');
 });
4. Local registration

If you want to register local instructions, The component also accepts a directives option

directives: {
  focus: {
    // 指令的定义
    inserted: function (el) {
      el.focus()
    }
  }
}
5. Customize the instructions for dragging elements

Vue.directive('drag', function (el) {
  el.onmousedown = function (e) {
    //获取鼠标点击处分别与p左边和上边的距离:鼠标位置-p位置
    var disX = e.clientX - el.offsetLeft;
    var disY = e.clientY - el.offsetTop;
    console.log(disX, disY);
    //包含在onmousedown里面,表示点击后才移动,为防止鼠标移出p,使用document.onmousemove
    document.onmousemove = function (e) {
      //获取移动后p的位置:鼠标位置-disX/disY
      var l = e.clientX - disX;
      var t = e.clientY - disY;
      el.style.left = l + 'px';
      el.style.top = t + 'px';
    }
    //停止移动
    document.onmouseup = function (e) {
      document.onmousemove = null;
      document.onmouseup = null;
    }
  }
});

2. Life cycle

beforeCreate(): The component instance has just been created.

Data observation and event configuration have not yet been carried out//Don’t be misled by beforeCreate here. In fact, the component instance has been created

created(): The instance has been created and

has been completed Data observation, operation of properties and methods, watch/event event callbacks. //Commonly used! ! !

beforeMount(): Before the template is compiled, it has not been mounted yet, and the page has not yet been displayed, but

the virtual Dom has been configured //First occupy the pit, and then mount it later Render the value when mounting

mounted(): After the template is compiled, it has been mounted.

The page will be rendered only at this time, and you can see the display of data on the page //Commonly used! ! !

Note: mounted does not promise that all sub-components will be mounted together. If you want to wait until the entire view is rendered, you can replace mounted with vm.$nextTick

beforeUpdate(): before component update

updated(): component update After

beforeDestroy(): Before the component is destroyed

destroyed(): After the component is destroyed

Vue2.0 custom directives and instance properties and methods##3. Calculated properties

1. Basic usage

Computed attributes are also used to store data, but they have the following characteristics:

**a. Data can be logically processed

b. Calculation Monitor the data in the attributes**


2. Calculated properties vs. ordinary properties

You can bind calculated properties in the template just like binding ordinary properties. There are differences in definitions:

The attribute value of a calculated attribute must be a function

data:{ //普通属性
  msg:'welcome to beijing',
},
computed:{ //计算属性
  msg2:function(){ //该函数必须有返回值,用来获取属性,称为get函数
    return '欢迎来到北京';
  },
  reverseMsg:function(){
  //可以包含逻辑处理操作,同时reverseMsg依赖于msg,一旦msg发生变化,reverseMsg也会跟着变化
    return this.msg.split(' ').reverse().join(' ');
 }
}
3. Calculated attribute vs method

Similar functions can also be achieved by defining the get function of the calculated attribute as a method

Difference:

a. Computed properties are updated based on its dependencies, and changes can only be updated when related dependencies change

b. Computed properties are cached. As long as the relevant dependencies have not changed, the value obtained by accessing the calculated property multiple times is the previously cached calculation result and will not be executed multiple times.

4. get and set

Computed properties are composed of two parts: get and set, which are used to obtain and set calculated properties respectively.

The default is only get. If you need set, you need to add it yourself. In addition, set does not directly modify the calculated attribute, but modifies its dependencies.

computed: {
  fullName: {
    // getter
    get: function () {
      return this.firstName + ' ' + this.lastName
    },
    // setter
    set: function (newValue) {
      //this.fullName = newValue 这种写法会报错
      var names = newValue.split(' ')
      this.firstName = names[0]//对它的依赖进行赋值
      this.lastName = names[names.length - 1]
    }
  }
}

Now when running vm.fullName = 'John Doe', the setter will be called, vm.firstName and vm.lastName will be updated accordingly.

4. Attributes and methods of instances

1. Attributes

vm.$el:Vue实例使用的根 DOM 元素
vm.$data:获取数据对象data
vm.$options:获取自定义属性
vm.$refs:一个对象,持有注册过 ref 特性的所有 DOM 元素和组件实例

You can understand these attributes by looking at an example:

<p>
   {{msg}}
   </p><h2 id="你好">你好</h2>
   <p>世界</p>    <hr>
   <h1 id="标题-name">标题:{{name}}</h1>

...
var vm=new Vue({
    el:'#itany',
    data:{
         msg:'welcome to beijing'
    },
    name:'tom',
    show:function(){
         console.log('show');
    }
});
// vm.属性名 获取data中的属性
   console.log(vm.msg);//welcome to beijing
// vm.$el 获取vue实例关联的元素
   console.log(vm.$el); //DOM对象
   vm.$el.style.color='red';
// vm.$data //获取数据对象data
   console.log(vm.$data);
   console.log(vm.$data.msg);
// vm.$options //获取自定义属性
   console.log(vm.$options.name);
   vm.$options.show();
// vm.$refs 获取所有添加ref属性的元素
   console.log(vm.$refs);
   console.log(vm.$refs.hello); //DOM对象
   vm.$refs.hello.style.color='blue';

Finally get the result As shown below:


Vue2.0 custom directives and instance properties and methods2. Method

vm.$mount():手动挂载vue实例//vm.$mount('#itany');
vm.$destroy():销毁实例
vm.$nextTick(callback):在DOM更新完成后再执行回调函数,一般在修改数据之后使用该方法,以便获取更新后的DOM
vm.$set(target, key, value)与Vue.set用法相同
vm.$delete(target, key)与Vue.delete用法相同
vm.$watch(data,callback[,options])数据监视

vm.$mount() usage scenario

var vm=new Vue({
   data:{
    msg:'欢迎来到南京网博',
    name:'tom'
    }
}).$mount('#itany');

vm .$nextTick() usage scenarios

<p>
   </p><h1 id="标题-name">标题:{{name}}</h1>

... var vm = new Vue({   el: '#itany',   data: {     msg: 'welcome to beijing',     name: 'tom'   } }); vm.name='汤姆';//页面展示已经更改过来了,但DOM还没更新完 //Vue实现响应式并不是数据发生改变之后DOM立即变化,需要按一定的策略进行DOM更新,需要时间!! console.log(vm.$refs.title.textContent);//标题:tom vm.$nextTick(function () { //DOM更新完成,更新完成后再执行此代码   console.log(vm.$refs.title.textContent);标题:汤姆 });

vm.$set(target, key, value)使用场景

参数:

{Object | Array} target

{string | number} key

{any} value

用法:向响应式对象中添加一个属性,并确保这个新属性同样是响应式的,且触发视图更新。它必须用于向响应式对象上添加新属性,因为Vue 无法探测普通的新增属性,比如 下面例子中的this.user.age=25,页面并不能展示{{this.age}}的数据

<p>
  <button>添加属性</button>
</p><hr>
  <h2 id="user-name">{{user.name}}</h2>
  <h2 id="user-age">{{user.age}}</h2>

...
var vm = new Vue({
  el: '#itany',
  data: {
    user: {
      id: 1001,
      name: 'tom'
    }
  },
  methods: {
    doAdd() {
      // this.user.age=25; //通过普通方式为对象添加属性时vue无法实时监视到
      // this.$set(this.user,'age',18); //通过vue实例的$set方法为对象添加属性,可以实时监视
      // Vue.set(this.user,'age',18);
      if (this.user.age) {
        this.user.age++;
      } else {
        Vue.set(this.user, 'age', 1);
      }
    }
  }
})

vm.$delete(target, key)使用场景

参数:

{Object | Array} target

{string | number} key

用途:删除对象的属性。如果对象是响应式的,确保删除能触发更新视图。

doDelete() {
  if (this.user.age) {
    // delete this.user.age; 此方法无效
    Vue.delete(this.user, 'age');
  }
}

vm.$watch( expOrFn, callback, [options] )使用场景

参数:

{string | Function} expOrFn

{Function | Object} callback

{Object} [options]


    • {boolean} deep:为了发现对象内部值的变化,可以在选项参数中指定 deep: true 。注意监听数组的变动不需要这么做。

    • {boolean} immediate

    用途:观察 Vue 实例变化的一个表达式或计算属性函数。回调函数得到的参数为新值和旧值。

<p>
  <input>
    </p><h3 id="name">{{name}}</h3>
    <hr>
  <input>
    <h3 id="age">{{age}}</h3>
    <hr>
  <input>
    <h3 id="user-name">{{user.name}}</h3>

...
var vm = new Vue({
  el: '#itany',
  data: {
    name: 'tom',
    age: 23,
    user: {
      id: 1001,
      name: 'alice'
    }
  },
  watch: { //方式2:使用vue实例提供的watch选项
    age: (newValue, oldValue) => {
      console.log('age被修改啦,原值:' + oldValue + ',新值:' + newValue);
    },
    user: {
      handler: (newValue, oldValue) => {
        console.log('user被修改啦,原值:' + oldValue.name + ',新值:' + newValue.name);
      },
      deep: true //深度监视,当对象中的属性发生变化时也会监视
    }
  }
});

//方式1:使用vue实例提供的$watch()方法
vm.$watch('name', function (newValue, oldValue) {
  console.log('name被修改啦,原值:' + oldValue + ',新值:' + newValue);
});
当对象中的属性发生变化时,也可以采用这种办法
vm.$watch("user",function(newValue,oldValue){
  console.log('user被修改啦,原值:'+oldValue.name+',新值:'+newValue.name);
},true)

Vue2.0 custom directives and instance properties and methods

以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!

相关推荐:

如何使用NodeJS + Lighthouse + Gulp搭建自动化网站性能测试的工具

关于Ajax如何实现跨域访问的问题介绍

The above is the detailed content of Vue2.0 custom directives and instance properties and methods. For more information, please follow other related articles on the PHP Chinese website!

Statement
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
From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool