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.
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):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 }
{{msg}}
... // 钩子函数的参数 Vue.directive('world', { bind(el, binding) { console.log(el);//指令所绑定的元素,DOM对象 el.style.color = 'yellow'; console.log(binding); } });
//传入一个简单的函数,bind和update时调用 Vue.directive('wbs',function(){ alert('wbs17022'); });
directives: { focus: { // 指令的定义 inserted: function (el) { el.focus() } } }
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; } } });
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 andhas 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, butthe 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 withvm.$nextTick
beforeUpdate(): before component update updated(): component update After beforeDestroy(): Before the component is destroyed destroyed(): After the component is destroyed##3. Calculated properties
**a. Data can be logically processed
b. Calculation Monitor the data in the attributes**
2. Calculated properties vs. ordinary properties
data:{ //普通属性 msg:'welcome to beijing', }, computed:{ //计算属性 msg2:function(){ //该函数必须有返回值,用来获取属性,称为get函数 return '欢迎来到北京'; }, reverseMsg:function(){ //可以包含逻辑处理操作,同时reverseMsg依赖于msg,一旦msg发生变化,reverseMsg也会跟着变化 return this.msg.split(' ').reverse().join(' '); } }
Difference:
a. Computed properties are updated based on its dependencies, and changes can only be updated when related dependencies changeb. 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
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
vm.$el:Vue实例使用的根 DOM 元素 vm.$data:获取数据对象data vm.$options:获取自定义属性 vm.$refs:一个对象,持有注册过 ref 特性的所有 DOM 元素和组件实例
{{msg}}
你好
世界
标题:{{name}}
... 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:
2. 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])数据监视
var vm=new Vue({ data:{ msg:'欢迎来到南京网博', name:'tom' } }).$mount('#itany');
标题:{{name}}
vm.$set(target, key, value)使用场景
参数:
{Object | Array} target
{string | number} key
{any} value
用法:向响应式对象中添加一个属性,并确保这个新属性同样是响应式的,且触发视图更新。它必须用于向响应式对象上添加新属性,因为Vue 无法探测普通的新增属性,比如 下面例子中的this.user.age=25,页面并不能展示{{this.age}}的数据
{{user.name}}
{{user.age}}
... 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 实例变化的一个表达式或计算属性函数。回调函数得到的参数为新值和旧值。
{{name}}
{{age}}
{{user.name}}
... 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)
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!
相关推荐:
如何使用NodeJS + Lighthouse + Gulp搭建自动化网站性能测试的工具
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!