Vue的基础知识点

130 阅读1分钟

1、vue.nextTick()使用方法

1、定义

下一个DOM更新循环结束之后回调。什么是DOM更新循环?data数据发生变化,DOM节点不会立即变化,会等一段时间后再更新DOM。因此更新DOM的过程叫做更新循环。

2、使用例子

以下例子说明,data数据变化,但是DOM节点却还是原来的值:


<template>
  <div class="hello">
    <div>
      <button id="firstBtn" @click="testClick()" ref="aa">{{testMsg}}</button>
    </div>
  </div>
</template>
 
<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      testMsg:"原始值",
    }
  },
  methods:{
    testClick:function(){
      let that=this;
      that.testMsg="修改后的值";
      console.log(that.$refs.aa.innerText);   //that.$refs.aa获取指定DOM,输出:原始值
    }
  }
}
</script>

可以看到aa节点使用了testMsg的值,在data内,testMsg已经更变为新值,但是打印出来的aa.innerText却还是原来的testMsg。这就说明了data里的值发生改变,DOM里的值不会立刻发生改变。

如果想要获取DOM里的值,并且想要确保DOM里的值是更新后的值,应该修改代码如下:

 methods:{
    testClick:function(){
      let that=this;
      that.testMsg="修改后的值";
      that.$nextTick(function(){
        console.log(that.$refs.aa.innerText);  //输出:修改后的值
      });
    }

2、vue.extend与vue.component区别

1、vue.extend

它需要一个参数,这个参数是包含Vue组件选项的对象。什么是包含组件选项的对象?任何一个.vue对象就是一个Vue组件选项的对象

var Toast = Vue.extend({
  template: `
    <div>
      <p v-if="flag">hello, {{name}}</p>
      <button @click="welcome">欢迎标语</button>
    </div>`,
  data () {
    return {
      name: 'zhangsan',
      flag: false
    }
  }
})

它的返回值是一个组件构造器。(上面的hello就是一个组件构造器)调用组件构造器可以返回一个组件实例。

let toastinstance = new Toast();

现在toastinstance就是一个Vue实例。再把Vue实例挂在到一个DOM上:

toastinstance.$mount(document.createElement('div'));

然后把这个DOM添加到body的末尾:

document.body.append(toastinstance.$el);

以后想在每个Vue对象上都拿到toast:

Vue.prototype.$toast = toastinstance;

2、Vue.conponent

注册全局组件

import Vue from 'vue'; 
// 引入loading组件 
import Loading from './loading.vue'; 
// 将loading注册为全局组件,在别的组件中通过<loading>标签使用Loading组件 
Vue.component('loading', Loading);

3、Vue的常用生命周期钩子

image.png