Vue2.0 Notes - Vue Common Instance Properties, Instance Methods

instance properties

  • vm.$el
  • vm.$data
  • vm.options
  • vm.$refs
  • vm.$root

vm.$el

This instance attribute is used to obtain the root DOM element used by the Vue instance, that is, the element DOM pointed to by the el option

<body>
<div id="app">
    <h4>你好,这是四级标题</h4>
    <p>这是一个段落,我什么都不想说</p>
</div>
<button onclick="getEl()">获得el选项的DOM元素</button>
<script>
    var vm = new Vue({
        el:'#app'
    })
    function getEl(){
        console.log(vm.$el);//获得DOM元素
        vm.$el.style.color='red';//设置字体颜色
    }
</script>
</body>

vm.$data

The data object that the Vue instance observes. The Vue instance proxies access to its data object property.
That is, you can access the data in the data option.

<button onclick="getData()">vm.$data获得数据值</button>
data:{
    msg:'你好你好',
    arr:['what','are','you','doing','?']
}
function getData(){
    console.log(vm.$data.msg);
    console.log(vm.$data.arr.join(' '));
}

Get the msg attribute, get the arr array, and generate a string by join.

vm.$options

Initialization options for the current Vue instance. Useful when you need to include custom properties in options. :

var vm = new Vue({
    el:'#app',
    data:{
        msg:'你好你好',
        arr:['what','are','you','doing','?']
    },
    name:'小小陈先森',
    user:{name:'小小陈先森',age:18,sex:'男'},
    show(){
            console.log(this.user.sex);
    }
})

console.log(vm.$options.name);
console.log(vm.$options.user.age);
console.log(vm.$options.show());

This custom attribute is the attribute or method function defined at the same level as the data option. Calls can be manipulated through $options.

vm.$refs

Returns all DOM elements and component instances that hold the registered ref attribute, the type is Object, and is read-only.
Because there are many refs, the component instance is obtained by .name.

<input type="text" ref="name" value="this is text"/>
<p ref="hello">HelloWorld</p>

console.log(vm.$refs.hello);
vm.$refs.name.value='whats';//.style.color='red';

No setting is required in the Vue instance, as long as the element holding the ref attribute is in the root node element.

vm.$root

The root Vue instance of the current component tree. If the current instance has no parent, this instance will be itself.

console.log(vm.$root);

If there is only one instance of vm, then vm.$root will return to itself, which is directly equivalent to vm.

Several other instance properties will be introduced when explaining components , and components are very important.

Instance methods (data manipulation)

vm.$watch

grammar:

vm.$watch( expOrFn, callback, [options] )

Watch an expression or computed property function in a Vue instance for changes. Watch for a property, and if it is changed, a callback function will be executed.
Expressions only accept supervised key paths. For more complex expressions, replace with a function.

  • The first argument is an expression or computed property function, which can also be a property.
  • The second parameter is the triggered callback function
  • The third parameter is the options that can be added
    <input type="text" v-model="msg">
    data:{
    msg:'你好你好'
    }
    vm.$watch('msg',function(newVal,oldVal){
    console.log('新值为:' + newVal + ',旧值为:' +oldVal);
    });

    You can set the first parameter as a computed property function.

    vm.$watch(
        function(){
            return Number(this.a) +Number(this.b);
        },
        function(newVal,oldVal){
            console.log('新值为:' + newVal + ',旧值为:' +oldVal);
        }
    );

    In addition, vm.$watch returns a cancel watch function to stop triggering the callback:

    var unwatch = vm.$watch('a', cb)
    // 之后取消观察
    unwatch()

    Once the unwatch() function is executed, the callback is not fired and it is no longer monitored.

    [options] Optional parameter, you can put the value deep: true for deep monitoring.
    immediate: true, triggers the callback immediately with the current value of the expression.
    In addition, the vm.$watch method has the same effect as the instance's watch option.

vm.$set

grammar:

vm.$set( target, key, value )

parameter:

  • {Object | Array} target
  • {string | number} key
  • {any} value
    sets a property of the object. If the object is reactive, make sure the property is also reactive when created, and trigger the view update
    Example:

    data:{
    user:{
        id:1001,
            name:'tom'
        }
    }
    
    //通过普通方式为对象添加属性时vue无法实时监视到
    this.user.age=25;
    //通过vue实例的$set方法为对象添加属性,可以实时监视
    this.$set(this.user,'age',18); 
    //通过全局API方式设置,全局API在后面介绍
    Vue.set(this.user,'age',22);

    Note that the object cannot be a Vue instance, or the root data object of a Vue instance

vm.$delete

grammar:

Vue.delete( target, key )

parameter:

  • {Object | Array} target
  • {string | number} key/index

    Array + index usage is only supported in version 2.2.0+.

Delete the properties of the object. If the object is reactive, make sure the delete triggers an update to the view.

//使用js的方式无效
delete this.user.age; 
//使用vm.$delete
vm.$delete(this.user,'name');
//使用全局API的方式
Vue.delete(this.user,'age');

The target object cannot be a Vue instance or the root data object of a Vue instance.

Instance Methods (Event Actions)

vm.$on,vm.$emit

grammar:

vm.$on( event, callback )

Listen for custom events on the current instance. Events can be triggered by vm.$emit. The callback function will receive all additional parameters passed to the event trigger function.
grammar:

vm.$emit( event, […args] )

Triggers an event on the current instance. Additional parameters are passed to the listener callback.
Example:

<div id="app">
    <p v-on:click="test($event,'123')">自定义事件</p>
</div>
methods:{
    test(event,num){
        vm.$emit('test',num);
    }
}

vm.$on('test',function(num){
    console.log('已监听,并执行回调函数');
    console.log('获得的值为:' + num);
});

When the p tag text is clicked, the custom click event test will be triggered, and we can perform the clicked operation in the test function.
By listening to this custom test event through vm.$on, the callback function can be executed, but it needs to be triggered by the vm.$emit method. The first parameter is the custom event name, and the second parameter is the additional parameter.

The vm.$emit method is also used in parent-child components to pass data up from child components.

vm.$once

grammar:

vm.$once( event, callback )

Listen for a custom event, but fire it only once, remove the listener after the first fire.
Example:

<button v-on:mouseover="mouseover">只执行一次监听</button>

methods:{
    mouseover(){
        console.log('移动到了此节点')
        vm.$emit('mouseover');//可随时,在任何处触发.
    }
}

vm.$once('mouseover',function(){
    console.log('已监听,并执行回调函数');
});

Through the test, it is found that the first time the button is touched, it will print "moved to this node", "monitored and executed the callback function", but when it is touched for the second time, only "moved to this node" will be printed. The monitored callback function will not be called because it is no longer being monitored.

vm.$off

grammar:

vm.$off( [event, callback] )

Remove custom event listeners.

  • If no parameter is provided, remove all event listeners;
  • If only an event is provided, remove all listeners for the event;
  • If both an event and a callback are provided, only the listener for this callback is removed.

instance methods (lifecycle)

vm.$mount

grammar:

vm.$mount( [elementOrSelector] )

If a Vue instance does not receive the el option when instantiated, it is in an "unmounted" state with no associated DOM element. An unmounted instance can be mounted manually using vm.$mount().
This method returns the instance itself, so other instance methods can be chained.
Example:

vm.$mount('#app');
//或
var vm=new Vue({
    data:{
        msg:'小小陈先森',
        name:'tom'
    }
}).$mount('#app');

View Vue instance life cycle

vm.$forceUpdate()

Force the Vue instance to re-render. Note that it only affects the instance itself and subcomponents that insert the contents of the slot, not all subcomponents.

vm.$nextTick( [callback] )

Delay callback execution until after the next DOM update loop. Use it immediately after modifying the data, then wait for the DOM to update.
The callback function is executed after the DOM update is completed . Generally, this method is used after modifying the data in order to obtain the updated DOM.
As a small example:

<p ref="thisP">{{name}}</p>

data:{
    name:'小小陈先森'
}
//js代码
vm.name='Tom';
console.log(vm.$refs.thisP.textContent);

If you don't add the .textContent of the last line, then you have no data error in execution.
Set to "Tom" value, console.log is still "Tom". If you add .textContent or its content.
You will find that although the value is set to "Tom", the print console is still "Little Chen Xiansen".
Reason:
As mentioned in the introduction of this function, Tom is displayed when the instance is rendered and loaded, but because the view needs to be rendered after the Vue data is updated , it is necessary to wait for the DOM to be updated before displaying the new value, and the js code executes It is faster, and the content is obtained directly through .$refs, and the DOM loading and rendering can not be waited for.
And this method is to deal with it.
Code:

vm.$nextTick(function(){
    console.log(vm.$refs.thisP.textContent);
});

Put it in the callback function, and after the DOM is executed, execute the callback function. That's enough.

vm.$destroy()

Completely destroys an instance. Clean up its connections to other instances and unbind all its directives and event listeners.
Hooks that trigger beforeDestroy and destroyed.

In most scenarios you should not call this method. It is best to use v-if and v-for directives to control the lifecycle of child components in a data-driven manner.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326173482&siteId=291194637