vue實(shí)現(xiàn)公共方法抽離
demo:制作一個(gè)點(diǎn)擊按鈕增加或者減少數(shù)字
現(xiàn)在vue組件內(nèi)部測試一下功能
<template><div class='all'><p>還未抽離</p><button @click='SubNum()'>-</button><input type='number' v-model='number'><button @click='AddNum()'>+</button></div></template><script>export default {data() {return {number: 0};},methods: {SubNum() {this.number--;if (this.number <= 0) {this.number = 0;}},AddNum() {this.number++;if (this.number > 10) {this.number = 10;}}}};</script>

效果還可以,至少方法是對的,接下來進(jìn)行方法抽離和傳送參數(shù)
首先新建一個(gè)js文件 common.js
用es6的export default將方法導(dǎo)出
export default {AddNum:function(){console.log(1)},SubNum:function(){console.log(2)}}
在main.js中用import將文件導(dǎo)入
import Common from ’./common’
聲明全局common
Vue.prototype.common = Common
現(xiàn)在組件內(nèi)只剩button和input,方法已經(jīng)剪切出去
<template><div class='all'><p>即將抽離</p><button @click='common.SubNum()'>-</button><input type='number' v-model='number'><button @click='common.AddNum()'>+</button></div></template><script>export default {data() {return {number: 0};},methods: {}};</script><style lang='scss' scoped type='text/css'></style>
點(diǎn)擊打印1或者2

證明方法是行得通的,現(xiàn)在將組件內(nèi)的參數(shù)傳送到方法里
傳參通過鉤子函數(shù)內(nèi)傳過去,因?yàn)橐壎c(diǎn)擊事件,所以直接在methods定義一個(gè)方法
<template><div class='all'><p>已經(jīng)抽離</p><button @click='add(booleans)'>-</button><input type='number' v-model='number'><button @click='add(!booleans)'>+</button></div></template><script>export default {data() {return {number: 0,booleans: false};},mounted() {},methods: {//判斷點(diǎn)擊的是加還是減add(booleans) {this.number = this.common.func(this.number,booleans);}}};</script><style lang='scss' scoped type='text/css'></style>
這時(shí)公共方法已經(jīng)簡化,這樣的話 在組件中看的比較簡潔
export default {func(num,booleans){if(booleans){num++if(num>=10){return 10}}else{num--if(num<=0){return 0}}return num}}

<--------文末------------>
有一個(gè)坑
<button @click='common.SubNum(number)'>-</button><input type='number' v-model='number'><button @click='common.AddNum(number)'>+</button>//export default {AddNum:function(num){num++if(num>=10){return 10}console.log(num)return num},SubNum:function(num){num--if(num<=0){console.log(num)return 0}return num}}
這個(gè)是剛開始抽離方法 直接在@click內(nèi)傳參
但是點(diǎn)擊事件并沒有將input的內(nèi)容修改
我的理解是只是將參數(shù)傳到方法里 但是方法改變參數(shù)時(shí)并未改變input綁定的this.number
不知道各位大神有什么見解或者建議,共同學(xué)習(xí),希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 詳解Android studio 動(dòng)態(tài)fragment的用法2. 解決Android studio xml界面無法預(yù)覽問題3. 圖文詳解vue中proto文件的函數(shù)調(diào)用4. Spring Boot和Thymeleaf整合結(jié)合JPA實(shí)現(xiàn)分頁效果(實(shí)例代碼)5. php模擬實(shí)現(xiàn)斗地主發(fā)牌6. 什么是python的自省7. Vue封裝一個(gè)TodoList的案例與瀏覽器本地緩存的應(yīng)用實(shí)現(xiàn)8. vue 使用localstorage實(shí)現(xiàn)面包屑的操作9. .Net Core使用Coravel實(shí)現(xiàn)任務(wù)調(diào)度的完整步驟10. Vuex localStorage的具體使用

網(wǎng)公網(wǎng)安備