Home > Web Front-end > JS Tutorial > Vue2.0 custom directives and instance properties and methods

Vue2.0 custom directives and instance properties and methods

不言
Release: 2018-07-13 17:27:38
Original
4101 people have browsed it

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 }
Copy after login
<p>
   </p><h3>{{msg}}</h3>

...
// 钩子函数的参数
Vue.directive('world', {
  bind(el, binding) {
    console.log(el);//指令所绑定的元素,DOM对象
    el.style.color = 'yellow';
    console.log(binding); 
  }
});
Copy after login
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');
 });
Copy after login
4. Local registration

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

directives: {
  focus: {
    // 指令的定义
    inserted: function (el) {
      el.focus()
    }
  }
}
Copy after login
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;
    }
  }
});
Copy after login

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(' ');
 }
}
Copy after login
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]
    }
  }
}
Copy after login

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 元素和组件实例
Copy after login

You can understand these attributes by looking at an example:

<p>
   {{msg}}
   </p><h2>你好</h2>
   <p>世界</p>    <hr>
   <h1>标题:{{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';
Copy after login

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])数据监视
Copy after login

vm.$mount() usage scenario

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

vm .$nextTick() usage scenarios

<p>
   </p><h1>标题:{{name}}</h1>
Copy after login

... 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>{{user.name}}</h2>
  <h2>{{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);
      }
    }
  }
})
Copy after login

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

参数:

{Object | Array} target

{string | number} key

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

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

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

参数:

{string | Function} expOrFn

{Function | Object} callback

{Object} [options]


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

    • {boolean} immediate

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

<p>
  <input>
    </p><h3>{{name}}</h3>
    <hr>
  <input>
    <h3>{{age}}</h3>
    <hr>
  <input>
    <h3>{{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)
Copy after login

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!

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