Vue基本用法3

1.自定义指令

指令是用来做dom操作的,如果vue现有的指令不能满足开发要求,我们需要对普通DOM元素进行底层操作,这时候就会用到自定义指令。

定义一个全局指令,让input框自动获取焦点

Vue.directive('focus',{
  inserted:function(el,binding){
    el.focus();
    el.style.background = 'gold';
    console.log(binding.name);
  }     
})
......

<div id="app">    
  <input type="text" v-focus>
</div>

如果定义成vue对象局部的,可以用vue对象的directives属性:

directives: {
  focus: {
    inserted: function (el,binding) {
      el.focus();
      el.style.background = 'gold';
      console.log(binding.name);
    }
  }
}

2.实例生命周期

每个Vue实例在被创建时都要经过一系列的初始化过程——例如,需要设置数据监听、编译模板、将实例挂载到DOM并在数据变化时更新 DOM 等。同时在这个过程中会自动运行一些叫做生命周期钩子的函数,我们可以使用这些函数,在实例的不同阶段加上我们需要的代码,实现特定的功能。

beforeCreate

在实例初始化之后,数据观测 (data observer) 和 event/watcher 事件配置之前被调用。

created

在实例创建完成后被立即调用。在这一步,实例已完成以下的配置:数据观测 (data observer),属性和方法的运算,watch/event 事件回调。然而,挂载阶段还没开始

beforeMount

在挂载开始之前被调用:相关的 render 函数首次被调用。

mounted

实例挂载到dom之后被调用,可以当成是vue对象的ready方法来使用,一般用它来做dom的初始化操作。

beforeUpdate

数据发生变化前调用

updated

数据发生变化后调用

3.数据交互

vue.js没有集成ajax功能,要使用ajax功能,可以使用vue官方推荐的axios.js库来做ajax的交互。 axios库的下载地址:https://github.com/axios/axios/releases

axios完整写法:

axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

axios请求的写法也写成get方式后post方式。

执行get请求

// 为给定 ID 的 user 创建请求
// then是请求成功时的响应,catch是请求失败时的响应

axios.get('/user?ID=12345')
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
  console.log(error);
});


// 可选地,上面的请求可以这样做
axios.get('/user', {
  params: {
    ID: 12345
  }
})
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
  console.log(error);
});

执行post请求

axios.post('/user', {
  firstName: 'Fred',
  lastName: 'Flintstone'
})
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
  console.log(error);
});

猜你喜欢

转载自blog.csdn.net/weixin_31449201/article/details/82053838