一、Vue.use與Vue.prototype的區(qū)別和用法
1、Vue.use和Vue.prototype區(qū)別
相同點(diǎn):都是注冊(cè)插件的方式,沒(méi)有本質(zhì)區(qū)別,都是在vue.prototype上添加了一個(gè)方法
不同點(diǎn):vue.use適用于注冊(cè)vue生態(tài)內(nèi)的插件(vuex、router、elementUI),vue.prototype適用于注冊(cè)生態(tài)外的插件(echarts、);
文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-695192.html
//1.1、vue.prototype用法
需要設(shè)置全局變量,在main.js中,Vue實(shí)例化的代碼里添加。 不想污染全局作用域。這種情況下,你可以通過(guò)在原型上定義它們使其在每個(gè)Vue實(shí)例中可用。
vue.prototype.$echarts = echarts //變量前加上$,是防止被組件中的變量意外覆蓋
//1.2vue.use用法
通過(guò)全局方法Vue.use()使用插件
Vue.usew會(huì)自動(dòng)阻止多次注冊(cè)插件
它需要在你調(diào)用new Vue()啟動(dòng)應(yīng)用之前完成
注意:Vue.use() 方法至少傳入一個(gè)參數(shù),該參數(shù)類(lèi)型必須是 Object 或 Function,如果是 Object 那么這個(gè) Object 需要定義一個(gè) install方法,如果是Function那么這個(gè)函數(shù)就被當(dāng)做install方法。在 Vue.use()執(zhí)行時(shí)install會(huì)默認(rèn)執(zhí)行,當(dāng)install執(zhí)行時(shí)第一個(gè)參數(shù)就是Vue,其他參數(shù)是Vue.use()執(zhí)行時(shí)傳入的其他參數(shù)。
2、vue的封裝和公共方法的調(diào)用
方式一:?jiǎn)蝹€(gè)組件以及公共組件的使用
//方式一
1.在vue項(xiàng)目中src/assets/js/創(chuàng)建js文件 例:如文章下面的common.js文件
2.在main.js引用common->然后實(shí)例化
/*引入公共函數(shù)*/
import common from './assets/js/common'
Vue.use(common);
3、在任何.vue組件中的生命周期利用this.方法名調(diào)用,因?yàn)橐呀?jīng)在main.js全局實(shí)例化了
4、在單個(gè).vue組件中使用
4.1、在.vue文件中引入import { unique } from '%/utils/utils'
4.2、let params = unique(this.proportionArr)
common.js文件————>//公共方法
export default{
install(Vue){
//這里是示例方法 getTime是方法名 function()可以攜帶參數(shù)
Vue.prototype.getTime = function(){
var date = new Date()
var y = date.getFullYear()
var m = date.getMonth() + 1
m = m < 10 ? ('0' + m) : m
var d = date.getDate()
d = d < 10 ? ('0' + d) : d
alert(y + m + d)
};
Date.prototype.Format = function(fmt){
let o = {
"M+": this.getMonth() + 1,
"d+": this.getDate(),
"h+": this.getHours(),
"m+": this.getMinutes(),
"s+": this.getSeconds(),
};
if(/(y+)/.test(fmt))
fmt = fmt.replace(RegExp.$1, (this.getFullYear() + '').substr(4 - RegExp.$1.length));
for(let k in o){
if(new RegExp("(" + k + ")").test(fmt))
fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
}
return fmt;
};
Vue.filter('formatDate', function(value,fmt){
if(!fmt) fmt = 'yyyy-MM-dd hh:mm:ss'
return new Date(value).Format(fmt)
});
Vue.prototype.throttle = function (fn,delay) {
var startTime = Date.now();
return function(){
let context = this;
let args = arguments;
let nowTime = Date.now();
if(nowTime-startTime >= delay){
fn.apply(context,args);
startTime = Date.now();
}
}
}
}
}
方式二:公共方法封裝方式(熟悉對(duì)外接口寫(xiě)法)
common2.js
//export命令用于規(guī)定模塊的對(duì)外接口,import命令用于輸入其他模塊提供的功能。
function _debounce(fn, delay = 200) {
var timer
return function() {
var th = this
var args = arguments
if (timer) {
clearTimeout(timer)
}
timer = setTimeout(function() {
timer = null
fn.apply(th, args)
}, delay)
}
}
// 節(jié)流
function _throttle(fn, interval = 200) {
var last
var timer
return function() {
var th = this
var args = arguments
var now = +new Date()
if (last && now - last < interval) {
clearTimeout(timer)
timer = setTimeout(function() {
last = now
fn.apply(th, args)
}, interval)
} else {
last = now
fn.apply(th, args)
}
}
}
export { _debounce, _throttle }
export function unique(arr) {
for (let i = 0; i < arr.length - 1; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i].id == arr[j].id) {
arr.splice(i, 1);
j--;
}
}
}
return arr;
}
二、class高階封裝
在ES6中,class (類(lèi))作為對(duì)象的模板被引入,可以通過(guò) class 關(guān)鍵字定義類(lèi)。class 的本質(zhì)是 function。它可以看作一個(gè)語(yǔ)法糖,讓對(duì)象原型的寫(xiě)法更加清晰、更像面向?qū)ο缶幊痰恼Z(yǔ)法。
?文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-695192.html
一、生成實(shí)例對(duì)象的傳統(tǒng)方法是通過(guò)構(gòu)造函數(shù)。
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.toString = function () {
return '(' + this.x + ', ' + this.y + ')';
};
var p = new Point(1, 2);
二、Es6通過(guò)class關(guān)鍵字,可以定義類(lèi);基本上,ES6 的 class 可以看作只是一個(gè)語(yǔ)法糖,它的絕大部分功能,ES5 都可以做到,新的class寫(xiě)法只是讓對(duì)象原型的寫(xiě)法更加清晰、更像面向?qū)ο缶幊痰恼Z(yǔ)法而已。
//上述方法用class實(shí)現(xiàn),使用的時(shí)候,也是直接對(duì)類(lèi)使用new命令,和構(gòu)造函數(shù)的用法完全一致。
class Point {
constructor(x, y){
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
四、ES6 的類(lèi),完全可以看作構(gòu)造函數(shù)的另一種寫(xiě)法(類(lèi)的數(shù)據(jù)類(lèi)型就是函數(shù),類(lèi)本身就指向構(gòu)造函數(shù));。
class Point {
// ...
}
typeof Point // "function"
Point === Point.prototype.constructor // true
五、事實(shí)上,類(lèi)的所有方法都定義在類(lèi)的prototype屬性上面
class Point {
constructor() {
// ...
}
toString() {
// ...
}
toValue() {
// ...
}
}
// 等同于
Point.prototype = {
constructor() {},
toString() {},
toValue() {},
//上述三個(gè)方法其實(shí)都是定義在Point.prototype上面。
};
六、注意:類(lèi)的內(nèi)部所有定義的方法,都是不可枚舉的
class Point {
constructor(x, y) {
// ...
}
toString() {
// ...
}
}
Object.keys(Point.prototype)//返回給定對(duì)象的所有可枚舉屬性的字符串?dāng)?shù)組
// []
Object.getOwnPropertyNames(Point.prototype)//返回一個(gè)數(shù)組,成員是參數(shù)對(duì)象自身的全部屬性的屬性名,不管該屬性是否可遍歷
// ["constructor","toString"]
3.1、class的constructor() 方法
3.3、constructor()方法是類(lèi)的默認(rèn)方法,通過(guò)new命令生成對(duì)象實(shí)例時(shí),自動(dòng)調(diào)用該方法。一個(gè)類(lèi)必須有constructor()方法,如果沒(méi)有顯式定義,一個(gè)空的constructor()方法會(huì)被默認(rèn)添加。
class Point {
}
// 等同于
class Point {
constructor() {}
}
3.4、類(lèi)的實(shí)例:類(lèi)的屬性和方法,除非顯式定義在其本身(即定義在this對(duì)象上),否則都是定義在原型上(即定義在class上)
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
var point = new Point(2, 3);
point.toString() // (2, 3)
point.hasOwnProperty('x') // true
point.hasOwnProperty('y') // true
point.hasOwnProperty('toString') // false
point.__proto__.hasOwnProperty('toString') // true
注意:上面代碼中,x和y都是實(shí)例對(duì)象point自身的屬性(因?yàn)槎x在this對(duì)象上),所以hasOwnProperty()方法返回true,而toString()是原型對(duì)象的屬性(因?yàn)槎x在Point類(lèi)上),所以hasOwnProperty()方法返回false。這些都與 ES5 的行為保持一致。
3.5、靜態(tài)方法:類(lèi)相當(dāng)于實(shí)例的原型,所有在類(lèi)中定義的方法,都會(huì)被實(shí)例繼承。如果在一個(gè)方法前,加上static關(guān)鍵字,就表示該方法不會(huì)被實(shí)例繼承,而是直接通過(guò)類(lèi)來(lái)調(diào)用,這就稱為“靜態(tài)方法”。
靜態(tài)方法: 類(lèi)相當(dāng)于實(shí)例的原型,所有在類(lèi)中定義的方法,都會(huì)被實(shí)例繼承。如果在一個(gè)方法前,加上static關(guān)鍵字,就表示該方法不會(huì)被實(shí)例繼承,而是直接通過(guò)類(lèi)來(lái)調(diào)用,這就稱為“靜態(tài)方法”。
class Foo {
static classMethod() {
return 'hello';
}
}
Foo.classMethod() // 'hello'
var foo = new Foo();
foo.classMethod(); // TypeError: foo.classMethod is not a function
注意,如果靜態(tài)方法包含this關(guān)鍵字,這個(gè)this指的是類(lèi),而不是實(shí)例。
class Foo {
static bar() {
this.baz();
}
static baz() {
console.log('hello');
}
baz() {
console.log('world');
}
}
Foo.bar() // hello
3.6、私有方法和私有屬性,是只能在類(lèi)的內(nèi)部訪問(wèn)的方法和屬性,外部不能訪問(wèn)。
class IncreasingCounter {
#count = 0;
get value() {
console.log('Getting the current value!');
return this.#count;
}
increment() {
this.#count++;
}
}
// #count就是私有屬性,只能在類(lèi)的內(nèi)部使用(this.#count)。如果在類(lèi)的外部使用,就會(huì)報(bào)錯(cuò)。
const counter = new IncreasingCounter();
counter.#count // 報(bào)錯(cuò)
counter.#count = 42 // 報(bào)錯(cuò)
3.7、通過(guò) extends 實(shí)現(xiàn)類(lèi)的繼承。
class Child extends Father { ... }
3.8、this指向
class Logger {
printName(name = 'there') {
this.print(`Hello ${name}`);
}
print(text) {
console.log(text);
}
}
const logger = new Logger();
const { printName } = logger;
printName(); // TypeError: Cannot read property 'print' of undefined
printName方法中的this,默認(rèn)指向Logger類(lèi)的實(shí)例。但是,如果將這個(gè)方法提取出來(lái)單獨(dú)使用,this會(huì)指向該方法運(yùn)行時(shí)所在的環(huán)境(由于class內(nèi)部是嚴(yán)格模式,所以 this 實(shí)際指向的是undefined),從而導(dǎo)致找不到print方法而報(bào)錯(cuò)。
一個(gè)比較簡(jiǎn)單的解決方法是,在構(gòu)造方法中綁定this,這樣就不會(huì)找不到print方法了。
class Logger {
constructor() {
this.printName = this.printName.bind(this);
}
// ...
}
或者
class Obj {
constructor() {
this.getThis = () => this;
}
}
const myObj = new Obj();
myObj.getThis() === myObj // true
到了這里,關(guān)于vue的公共方法封裝以及class高階封裝的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!