«

Vue的内置API

yang 发布于 阅读:362 Vue2阶段


1.1 ref属性

ref属性可以加在任意标签上,用于获取页面元素,相当于原生JS的id

设置ref属性:

<h1 ref="title">知识点:ref属性</h1>

通过ref获取元素:

mounted(){
    //通过ref获取页面元素
    console.log( this.$refs.title );
    this.$refs.title.style.background='#f00';
}

1.2 Vue.set方法

在Vue中,数据双向绑定是有缺陷的,只能通过Vue重写过的方法操作才能实现数据双向绑定,如果用未重写过的方法操作就不能实现实时更新,给对象添加新属性也不能实时更新,这里就需要 set 方法进行重新绑定

//修改数组元素
changeArr(){
    // this.arr[0]=5; //不能实时更新
    // this.arr.push('aaaa'); //可以实时更新,原因 .push() 方法是vue重写过的方法
    Vue.set(this.arr, 0, 5); //使用set方法重新绑定,就有实时更新了
    console.log(this.arr);
},

//修改对象属性
changeObj(){
   // this.obj.name='关羽'; //可以更新
   // this.obj.gender='男'; //不可以自动更新
   this.$set(this.obj, 'gender', '男'); //使用set方法重新绑定,就可以实时更新了
   console.log(this.obj);
}

1.3 Vue.nextTick

下一个节点,有两种用法 Vue.nextTick() 和 this.$nextTick()

created(){
    //nextTick() 下一个节点
    this.$nextTick( ()=>{
        console.log(this.$refs.title);
    });
},

1.4 Vue.filter全局过滤器

在main.js中注册全局过滤器,在任意组件中都可以直接使用

//全局过滤器
Vue.filter('fixed', function (num) {
  return num.toFixed(2);
});

1.5 Vue.component全局组件

在main.js中直接注册成为全局组件,可以在任意组件中直接使用

import MyButton from '@/components/MyButton.vue'
Vue.component('MyButton', MyButton)

1.6 Vue.use()

将vue.js的插件直接挂到Vue全局上

1.7 Vue.directive 自定义指令

在main.js中添加自定义指令,在任意组件中都可以直接使用该指令

Vue.directive('abc', {
  // 被绑定元素插入父节点时调用(渲染的时候调用)
  inserted: function (dom, o) {
    dom.style.width = o.value + 'px';
    dom.style.overflow = 'hidden';
    dom.style.whiteSpace = 'nowrap';
    dom.style.textOverflow = 'ellipsis';
  },
});

//使用指令
<h1 v-abc="200">今天星期六,我们在上课,好海哦</h1>

Vue的内置API

版权所有:微4e
文章标题:Vue的内置API
除非注明,文章均为 微4e 原创,请勿用于任何商业用途,禁止转载

推荐阅读:


扫描二维码,在手机上阅读
请先 登录 再评论