«

Vue内置API小结:ref属性、Vue.set、Vue.nextTick等

时间:2023-5-28 21:02     作者:六思逸     分类: Vue


Vue的内置API

ref属性

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

设置ref属性

<h1 ref="title">六思逸</h1>

通过ref获取元素

mounted(){
    console.log( this.$refs.title );
    this.$refs.title.style.background='#f00';
}

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);
}

Vue.nextTick

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

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

Vue.filter全局过滤器

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

Vue.filter('fixed', function (num) {
  return num.toFixed(2);
});

Vue.component全局组件

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

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

Vue.use()

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

// 定义一个插件对象 myPlugin
const myPlugin = {
  install(Vue, options) {
    // 在Vue原型上新增一个方法 myMethod
    Vue.prototype.$myMethod = function (message) {
      alert(`这是我的插件。${message}`);
    };
  }
};

// 使用插件
Vue.use(myPlugin);

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 Vue内置API ref属性 Vue.set Vue.nextTick Vue.filter Vue.component Vue.use Vue.directive

版权所有:六思逸
文章标题:Vue内置API小结:ref属性、Vue.set、Vue.nextTick等
除非注明,文章均为 六思逸 原创,转载请注明作者和出处 六思逸

扫描二维码,在手机上阅读

推荐阅读: