全局配置
错误信息提示,errorHandler
const errorHandler = (error, vm)=>{
console.error('抛出全局异常')
console.error(vm)
console.error(error)
// alert('全局异常'+JSON.stringify(error))
}
Vue.config.errorHandler = errorHandler
Vue.prototype.$throw = (error)=> errorHandler(error,this)
.catch(req=>{
this.$throw(req.msg)
})
全局配置
Vue.extend(options)
怎么使用,何时使用?
结合组件写js调用方法的dom插件时使用,比如vant中this.$toast
import Vue from 'vue';
import VueToast from './Toast';
if (!queue.length || multiple) {
const toast = new (Vue.extend(VueToast))({
el: document.createElement('div'),
});
toast.$on('input', (value) => {
toast.value = value;
});
queue.push(toast);
}
this.#nextTick()
在下次DOM更新循环结束之后执行延迟回调。在修改数据之后立即使用这个方法,获取更新后的DOM。
//方法一 function then
handleProfile(){
this.msg = 'hello word 已更新'
console.log(this.$el.textContent) // => '未更新'
this.$nextTick(function () {
// DOM 更新了
console.log(this.$el.textContent) // => '已更新'
})
//因为 $nextTick() 返回一个 Promise 对象
// this.$nextTick().then(()=>{
// // DOM 更新了
// console.log(this.$el.textContent) // => '已更新'
// })
},
//方法三:因为 $nextTick() 返回一个 Promise 对象
handleAsync:async function (params) {
this.msg = 'async await hello word 已更新'
await this.$nextTick();
console.log(this.$el.textContent) // => '已更新'
}
this.$set( target, propertyName/index, value )
向响应式对象中添加一个 property,并确保这个新 property 同样是响应式的,且触发视图更新。
参数:
- {Object | Array} target
- {string | number} propertyName/index
- {any} value
返回值:设置的值。
注意:target是Object | Array
data() {
return {
setdata:{
name:'this.$set',
age:12
},
current:0,
loading:[true,true,true]
};
},
handleSetData(){
this.$set(this.setdata,'name','11111'); //Object
this.$set(this.loading,this.current,false); // Array
this.$delete(this.setdata,'age')
}
this.$delete(target, propertyName/index)
删除对象的 property。如果对象是响应式的,确保删除能触发更新视图。
use,component,mixin
main.js中 引入全局
- Vue.use() 安装 Vue.js 插件
- Vue.component() 注册或获取全局组件
- Vue.mixin() 全局注册一个混入
import ElementUI from "element-ui";
import 'element-ui/lib/theme-chalk/index.css';
import PageLoading from '@/components/PageLoading'
import mixin from "./mixin";
Vue.mixin(mixin)
Vue.use(ElementUI, { size: 'medium' })
Vue.component(PageLoading);
选项 / 数据
data
data是一个function
methods
存放方法的地方,直接通过 VM 实例访问这些方法,或者在指令表达式中使用。方法中的 this 自动绑定为 Vue 实例。
注意,不应该使用
箭头函数来定义 method 函数(例如 plus: () => this.a++)。理由是箭头函数绑定了父级作用域的上下文,所以 this 将不会按照期望指向 Vue 实例,this.a 将是 undefined。
computed
计算属性,所有 getter 和 setter 的 this 上下文自动地绑定为 Vue 实例。
示例:
<van-popup v-model="showPicker" position="bottom"></van-popup>
<template v-if="handleLogin"></template>
computed: {
// 仅读取
handleLogin() {
let store = this.$store.getters.user;
return store.loading
},
// 读取和设置
showPicker:{
get: function () {
return this.isShow
},
set:function (val) {
this.$emit('cancel')
},
},
},
watch
监听