Vue之定義全局工具類問題
vue定義全局工具類
解決方案
1.簡單的寫法
每次使用都需要import
test.js:
具體使用
2.定義全局工具類(實例屬性)
具體使用
3.定義全局工具類(插件)
全局注冊不需要import
例子:現(xiàn)需定義ValidateUtil工具類
utils/validate/index.js:
utils/index.js:
main.js:
具體使用
vue常用工具類方法匯總
1.利用Cookie,來設(shè)置接口攜帶的‘token’
執(zhí)行命令npm install js-cookie,在js工具類中引入,
/** @format */ import Cookie from 'js-cookie'; function getToken() { ? return Cookie.get('token'); } function setToken(token) { ? Cookie.set('token', token); } function removeToken() { ? Cookie.remove('token'); } export default { ? getToken, ? setToken, ? removeToken };
2.利用日期moment.js工具
來完成對周次以及星期的處理 ,包含了 獲取一年的每周的周次,以及每周的開始日期,結(jié)束日期,以及當前屬于星期幾等方法
執(zhí)行npm install moment.js
/** @format */ import moment from 'moment'; //獲取前一周的開始時間,結(jié)束時間,以及周數(shù) function getPreWeek(week) { ? if (isParamBlank(week)) { ? ? return; ? } ? var startDate = moment() ? ? .week(week - 1) ? ? .startOf('week') ? ? .add(1, 'days') ? ? .format('YYYY-MM-DD'); //這樣是年月日的格式 ? var endDate = moment() ? ? .week(week - 1) ? ? .endOf('week') ? ? .add(1, 'days') ? ? .format('YYYY-MM-DD'); ? var weekCount = moment(moment(startDate).subtract(1, 'days')).weeks(); ? var preWeekInfo = { ? ? startDate: startDate, ? ? endDate: endDate, ? ? weekCount: weekCount ? }; ? return preWeekInfo; } // 獲取下一周的起始日期和結(jié)束日期,以及周數(shù) function getNextWeek(week) { ? if (isParamBlank(week)) { ? ? return; ? } ? var startDate = moment() ? ? .week(week + 1) ? ? .startOf('week') ? ? .add(1, 'days') ? ? .format('YYYY-MM-DD'); //這樣是年月日的格式 ? var endDate = moment() ? ? .week(week + 1) ? ? .endOf('week') ? ? .add(1, 'days') ? ? .format('YYYY-MM-DD'); ? var weekCount = moment(moment(startDate).subtract(1, 'days')).weeks(); ? var nextWeekInfo = { ? ? startDate: startDate, ? ? endDate: endDate, ? ? weekCount: weekCount ? }; ? return nextWeekInfo; } // 根據(jù)傳入?yún)?shù),獲取周次信息 function getWeekInfoByDate(param) { ? if (isParamBlank(param)) { ? ? // 當前時間所在周數(shù) ? ? return; ? } ? var date = moment(param); ? var startDate = moment() ? ? .week(moment(date).week()) ? ? .startOf('week') ? ? .add(1, 'days') ? ? .format('YYYY-MM-DD'); //這樣是年月日的格式 ? var endDate = moment() ? ? .week(moment(date).week()) ? ? .endOf('week') ? ? .add(1, 'days') ? ? .format('YYYY-MM-DD'); ? var weekCount = moment(moment(startDate).subtract(1, 'days')).weeks(); ? // 獲取當前的周次 , 如果不穿參數(shù),則表示當前的周數(shù) ,如果傳入時間,則表示 該時間段所在的周數(shù) ? //因為是基于moment.js ?起始時間還是從周日開始算的 ,所以需要在現(xiàn)有的基礎(chǔ)上減去一天 ,這樣也是為了防止邊界情況出錯 ? var weekInfo = { ? ? startDate: startDate, ? ? endDate: endDate, ? ? weekCount: weekCount ? }; ? return weekInfo; } // ?獲取一年中的總周次 function getWeekTotalInYear() { ? return moment().weeksInYear(); } //校驗參數(shù)是否為空 function isParamBlank(param) { ? if (typeof param == 'undefined' || param == null || param.length == 0) { ? ? return true; ? } ? return false; } // 獲取當前周的周數(shù)以及該周的開始時間和結(jié)束時間 function getCurrentWeekInfo() { ? // var weekCount = moment( moment(moment().week(moment().week()).startOf('week')).subtract(1,'days')).weeks(); ? var weekCount = moment(moment().subtract(1, 'days')).weeks(); ? var startDate = moment() ? ? .week(weekCount) ? ? .startOf('week') ? ? .add(1, 'days') ? ? .format('YYYY-MM-DD'); //這樣是年月日的格式 ? var endDate = moment() ? ? .week(weekCount) ? ? .endOf('week') ? ? .add(1, 'days') ? ? .format('YYYY-MM-DD'); ? var currentWeekInfo = { ? ? startDate: startDate, ? ? endDate: endDate, ? ? weekCount: weekCount ? }; ? return currentWeekInfo; } function getDayByWeekDay(week, weekNum) { ? if (isParamBlank(week) && isParamBlank(weekNum)) { ? ? return; ? } ? return moment() ? ? .week(week) ? ? .startOf('week') ? ? .add(weekNum, 'days') ? ? .format('YYYY-MM-DD'); //這樣是年月日的格式 } //start of 2019-2-18 新增 //為了解決點擊上一周和下一周的 邊界值情況,新增以下兩個函數(shù) //點擊上一周 function clickPreIconGetPreWeek(week, currentWeekStartTime) { ? if (isParamBlank(week) && isParamBlank(currentWeekStartTime)) { ? ? return; ? } ? var startDate = moment(currentWeekStartTime) ? ? .subtract(7, 'days') ? ? .format('YYYY-MM-DD'); ? var endDate = moment(startDate) ? ? .add(6, 'days') ? ? .format('YYYY-MM-DD'); ? var weekCount = moment(moment(startDate).subtract(1, 'days')).weeks(); ? var preWeekInfo = { ? ? startDate: startDate, ? ? endDate: endDate, ? ? weekCount: weekCount ? }; ? return preWeekInfo; } //點擊下一周 function clickNextIconGetNextWeek( ? week, ? currentWeekStartTime, ? currentWeekEndTime ) { ? if (isParamBlank(week) && isParamBlank(currentWeekEndTime)) { ? ? return; ? } ? var startDate = moment(currentWeekStartTime) ? ? .add(7, 'days') ? ? .format('YYYY-MM-DD'); ? var endDate = moment(startDate) ? ? .add(6, 'days') ? ? .format('YYYY-MM-DD'); ? var weekCount = moment(moment(startDate).subtract(1, 'days')).weeks(); ? var nextWeekInfo = { ? ? startDate: startDate, ? ? endDate: endDate, ? ? weekCount: weekCount ? }; ? return nextWeekInfo; } //end ?of 2019-2-18 新增 export const dateUtils = { ? getPreWeek: getPreWeek, ? clickPreIconGetPreWeek: clickPreIconGetPreWeek, ? clickNextIconGetNextWeek: clickNextIconGetNextWeek, ? getNextWeek: getNextWeek, ? getWeekTotalInYear: getWeekTotalInYear, ? getCurrentWeekInfo: getCurrentWeekInfo, ? getWeekInfoByDate: getWeekInfoByDate, ? getDayByWeekDay: getDayByWeekDay };
3.vue自定義指令工具類
vue的全局自定義指令,
例如:當從一個獲取到焦點的input框 點擊另一個input框時,這個被點擊的input框不會自動獲取到焦點,這個時候就可以利用Vue.directive()自定義指令
/** @format */ /*Vue全局指令*/ import Vue from 'vue'; /** ?* Vue 跳轉(zhuǎn)指令'v-jump',基于router.push方式 ?* @param name/path 路由名或路徑(必傳)[eg:home或/home] ?* @param param 參數(shù)[eg:{id:123}] ?* @param type ?按什么方式傳遞參數(shù)[1-按路由配置方式[eg:home/123];2-按param方式[eg:{name/path:'',params:{id:123}}];3-按query方式(默認)[eg:{name/path:'',query:{id:123}}]] ?* 例子:<div class="click-wrap" :data-id="item.id" v-jump="['home_detail', {id:123}, 2]"> ?*/ Vue.directive('jump', { ? // el: 指令綁定的元素 ? // vm: 擁有該指令的上下文 ViewModel ? // expression: 指令的表達式,不包括參數(shù)和過濾器 ? // arg: 指令的參數(shù) ? // raw: 未被解析的原始表達式 ? // name: 不帶前綴的指令名 ? bind: function(el, binding, vnode) { ? ? // 做綁定的準備工作(比如添加事件監(jiān)聽器,或是其他只需要執(zhí)行一次的復(fù)雜操作) ? ? // 若和v-for指令共用,由于v-for的就地重用機制,需要指定一個唯一的key屬性(對應(yīng)vnode.key),如果沒有指定,這里需要修改 ? ? vnode.key = Math.round(Math.random() * 12568); ? ? el.handler = function() { ? ? ? let data = binding.value || null; ? ? ? if (data) { ? ? ? ? let vm = vnode.context; ? ? ? ? let pathName = data[0] || null; ? ? ? ? let param = data[1] || null; ? ? ? ? let type = data[2] || 3; ? ? ? ? // console.log('v-jump數(shù)據(jù):', pathName, param, type); ? ? ? ? if (pathName) { ? ? ? ? ? if (type === 1) { ? ? ? ? ? ? /*path類型單獨處理參數(shù)格式*/ ? ? ? ? ? ? if (param) { ? ? ? ? ? ? ? var pStr = []; ? ? ? ? ? ? ? for (let j in param) { ? ? ? ? ? ? ? ? if (param.hasOwnProperty(j)) { ? ? ? ? ? ? ? ? ? param[j] ? pStr.push(param[j]) : null; ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? } ? ? ? ? ? ? } ? ? ? ? ? ? vm.$router.push({ ? ? ? ? ? ? ? path: '/' + pathName + (param ? '/' + pStr.join('/') : '') ? ? ? ? ? ? }); ? ? ? ? ? } ? ? ? ? ? if (type === 2) { ? ? ? ? ? ? vm.$router.push({ name: pathName, params: param }); ? ? ? ? ? } ? ? ? ? ? if (type === 3) { ? ? ? ? ? ? vm.$router.push({ path: '/' + pathName, query: param }); ? ? ? ? ? } else { ? ? ? ? ? ? if (pathName.indexOf('/') > -1) { ? ? ? ? ? ? ? vm.$router.push({ path: pathName }); ? ? ? ? ? ? } else { ? ? ? ? ? ? ? vm.$router.push({ name: pathName }); ? ? ? ? ? ? } ? ? ? ? ? } ? ? ? ? } else { ? ? ? ? ? console.warn('好歹給個頁面名啊!'); ? ? ? ? } ? ? ? } else { ? ? ? ? console.error('v-jump似乎還需要點什么!'); ? ? ? } ? ? }; ? ? /*為Dom綁定事件*/ ? ? el.addEventListener('click', el.handler, false); ? }, ? update: function(newValue, oldValue) { ? ? // 根據(jù)獲得的新值執(zhí)行對應(yīng)的更新(對于初始值也會被調(diào)用一次) ? }, ? unbind: function(el) { ? ? // 做清理工作(比如移除在 bind() 中添加的事件監(jiān)聽器) ? ? /*為Dom移除事件*/ ? ? el.removeEventListener('click', el.handler); ? } }); /** ?* Vue 指令'v-open',打開新頁面 ?* @param name/path 路由名或路徑(必傳)[eg:home或/home] ?* @param param 參數(shù)[eg:{id:123}] ?* 例子:<div class="click-wrap" :data-id="item.id" v-open="['home_detail', {id:123}]"> ?*/ Vue.directive('open', { ? bind: function(el, binding, vnode) { ? ? vnode.key = new Date().getTime() * 3579; ? ? el.handler = function() { ? ? ? let data = binding.value || null; ? ? ? if (data) { ? ? ? ? let vm = vnode.context; ? ? ? ? let pathName = data[0] || null; ? ? ? ? let param = data[1] || null; ? ? ? ? // console.log('v-open數(shù)據(jù):', pathName, param); ? ? ? ? let routeData = vm.$router.resolve({ ? ? ? ? ? name: '新頁面打開', ? ? ? ? ? path: pathName, ? ? ? ? ? query: param ? ? ? ? }); ? ? ? ? window.open(routeData.href, '_blank'); ? ? ? } else { ? ? ? ? console.error('v-open似乎還需要點什么!'); ? ? ? } ? ? }; ? ? el.addEventListener('click', el.handler, false); ? }, ? unbind: function(el) { ? ? el.removeEventListener('click', el.handler); ? } }); /** ?* Vue input限制只能輸入正整數(shù)(可控制最小最大值) ?* 例子:<input type="text" v-integer="{min:1, max:10}"> ?*/ Vue.directive('integer', { ? bind: function(el, binding) { ? ? let attr = binding.value; //傳入的參數(shù) ? ? /* var position = binding.modifiers; //獲取對象數(shù)組,使用需要遍歷 ? ? var warning = binding.arg; //獲取true屬性 */ ? ? // console.log(attr); ? ? el.handler = function() { ? ? ? el.value = el.value.replace(/\D+/, ''); ? ? ? attr.max !== undefined ? ? ? ? ? el.value > attr.max ? ? ? ? ? ? (el.value = attr.max) ? ? ? ? ? : null ? ? ? ? : null; ? ? ? attr.min !== undefined ? ? ? ? ? el.value < attr.min ? ? ? ? ? ? (el.value = attr.min) ? ? ? ? ? : null ? ? ? ? : null; ? ? }; ? ? el.addEventListener('input', el.handler); ? }, ? unbind: function(el) { ? ? el.removeEventListener('input', el.handler); ? } }); /** ?* Vue 頁面顯示input框時自動獲取焦點 ?* 例子: ?*/ Vue.directive('myfocus', { ? inserted: function(el, binding) { ? ? // console.log(el); ? ? // let mtinput = el.querySelector('input'); ? ? el.focus(); ? } }); /* Vue.directive('blur', { ? bind: function(el, binding, vnode) { ? ? let mtinput = el.querySelector('input'); ? ? mtinput.onfocus = function() { ? ? ? //如果要對節(jié)點的數(shù)據(jù)進行更改,且更改要映射到頁面上,則更改可在vnode.context上進行,這樣,改完之后,改變就會映射到頁面 ? ? }; ? ? mtinput.onblur = function() { ? ? ? //同上理 ? ? }; ? }, ? unbind: function(el) { ? ? el.removeEventListener('input', el.handler); ? } }); */
4.vue支持render渲染函數(shù)
例如:vue+elemetn-ui 里面的table跟render進行搭配簡化代碼
在expand.js文件中這樣寫:
/** @format */ export default { ? name: 'TableExpand', ? functional: true, ? props: { ? ? row: Object, ? ? render: Function, ? ? index: Number, ? ? column: { ? ? ? type: Object, ? ? ? default: null ? ? } ? }, ? render: (h, ctx) => { ? ? const params = { ? ? ? row: ctx.props.row, ? ? ? index: ctx.props.index ? ? }; ? ? if (ctx.props.column) params.column = ctx.props.column; ? ? return ctx.props.render(h, params); ? } };
在common-table.vue文件中這樣寫
<!-- @format --> <template> ? <div class="common-table"> ? ? <el-table ? ? ? :data="tableData" ? ? ? @selection-change="handleSelectionChange" ? ? ? @sort-change="handleSortChange" ? ? ? stripe ? ? ? border ? ? ? :show-summary="summary.enable" ? ? ? :sum-text="summary.text" ? ? > ? ? ? <template v-for="item in columnsData"> ? ? ? ? <template v-if="item.type === 'options'"> ? ? ? ? ? <el-table-column ? ? ? ? ? ? :key="item.prop" ? ? ? ? ? ? :prop="item.prop" ? ? ? ? ? ? :label="item.label" ? ? ? ? ? ? :width="item.width" ? ? ? ? ? ? :sortable="item.sortable" ? ? ? ? ? ? :type="item.type" ? ? ? ? ? ? :show-overflow-tooltip="item.tooltip" ? ? ? ? ? > ? ? ? ? ? ? <template slot-scope="scope"> ? ? ? ? ? ? ? <expand :render="item.render" :row="scope.row" :column="item"> ? ? ? ? ? ? ? </expand> ? ? ? ? ? ? </template> ? ? ? ? ? </el-table-column> ? ? ? ? </template> ? ? ? ? <template v-else> ? ? ? ? ? <el-table-column ? ? ? ? ? ? :key="item.prop" ? ? ? ? ? ? :prop="item.prop" ? ? ? ? ? ? :label="item.label" ? ? ? ? ? ? :width="item.width" ? ? ? ? ? ? :sortable="item.sortable" ? ? ? ? ? ? :type="item.type" ? ? ? ? ? ? :show-overflow-tooltip="item.tooltip" ? ? ? ? ? ? :formatter="item.formatter" ? ? ? ? ? ? :selectable="item.selectable" ? ? ? ? ? > ? ? ? ? ? </el-table-column> ? ? ? ? </template> ? ? ? </template> ? ? </el-table> ? </div> </template> <script> /* 添加 ?render函數(shù)擴展 */ import Expand from '@/utils/expand'; export default { ? name: 'ComTable', ? components: { Expand }, ? props: { ? ? columnsData: { ? ? ? type: Array, ? ? ? default: () => { ? ? ? ? return []; ? ? ? }, ? ? ? required: true ? ? }, ? ? tableData: { ? ? ? type: Array, ? ? ? default: () => { ? ? ? ? return []; ? ? ? }, ? ? ? required: true ? ? }, ? ? summary: { ? ? ? type: Object, ? ? ? default: () => { ? ? ? ? return { ? ? ? ? ? enable: false, ? ? ? ? ? text: '合計' ? ? ? ? }; ? ? ? } ? ? } ? }, ? data() { ? ? return { ? ? ? multipleSelection: [] ? ? }; ? }, ? methods: { ? ? /** ? ? ?* 點擊三角形排序 ? ? ?* @param column ? ? ?*/ ? ? handleSortChange(column) { ? ? ? this.$emit('sortChange', column); ? ? }, ? ? /** ? ? ?* 實時獲取選擇數(shù)據(jù)數(shù)組 ? ? ?* @param val ? ? ?*/ ? ? handleSelectionChange(val) { ? ? ? this.multipleSelection = val; ? ? ? this.$emit('selectionChange', val); ? ? } ? } }; </script> <style scoped lang="less"> .common-table { ? margin: 20px 0; ? a.button { ? ? margin-top: 20px; ? ? height: 30px; ? ? line-height: 30px; ? ? width: 76px; ? ? text-align: center; ? ? border-radius: 2px; ? ? border: 1px solid #1d91ff; ? ? color: #1d91ff; ? ? background-color: #fff; ? ? float: left; ? } ? /deep/.el-table { ? ? thead { ? ? ? th { ? ? ? ? background-color: #f9fafb !important; ? ? ? } ? ? } ? } ? /deep/ .btn-option { ? ? cursor: pointer; ? ? margin-right: 10px; ? ? color: #349dff; ? } ? /deep/ .disabled { ? ? cursor: not-allowed; ? ? margin-right: 10px; ? ? color: #999; ? } ? /deep/ .btn-option:last-child { ? ? margin-right: 0px; ? } } </style>
在業(yè)務(wù)代碼中需要引用 common-tab.vue,這樣寫:
<!-- @format --> <!-- ?區(qū)管-系統(tǒng)管理 -資訊管理 頁 --> <template> ? <div class="room-manage"> ? ? <div class="search-form clearfix"> ? ? ? <el-form :inline="true"> ? ? ? ? <el-form-item label="資訊類型:"> ? ? ? ? ? <el-select v-model="param.columnCode" placeholder="請選擇資訊類型"> ? ? ? ? ? ? <el-option ? ? ? ? ? ? ? v-for="(item, index) in typeList" ? ? ? ? ? ? ? :key="index" ? ? ? ? ? ? ? :label="item.label" ? ? ? ? ? ? ? :value="item.value" ? ? ? ? ? ? ></el-option> ? ? ? ? ? </el-select> ? ? ? ? </el-form-item> ? ? ? ? <el-form-item label="發(fā)布者:"> ? ? ? ? ? <el-input ? ? ? ? ? ? v-model="param.author" ? ? ? ? ? ? placeholder="請輸入發(fā)布者姓名" ? ? ? ? ? ? clearable ? ? ? ? ? ></el-input> ? ? ? ? </el-form-item> ? ? ? ? <el-form-item label="資訊標題:"> ? ? ? ? ? <el-input ? ? ? ? ? ? v-model="param.title" ? ? ? ? ? ? placeholder="請輸入資訊標題" ? ? ? ? ? ? clearable ? ? ? ? ? ></el-input> ? ? ? ? </el-form-item> ? ? ? ? <el-form-item label="是否置頂:"> ? ? ? ? ? <el-select ? ? ? ? ? ? v-model="param.isTop" ? ? ? ? ? ? placeholder="是否置頂" ? ? ? ? ? ? style="width: 100px;" ? ? ? ? ? > ? ? ? ? ? ? <el-option label="全部" value=""></el-option> ? ? ? ? ? ? <el-option label="是" :value="0"></el-option> ? ? ? ? ? ? <el-option label="否" :value="1"></el-option> ? ? ? ? ? </el-select> ? ? ? ? </el-form-item> ? ? ? ? <el-form-item> ? ? ? ? ? <el-button type="warning" size="medium" @click="handleSearchList" ? ? ? ? ? ? >查詢</el-button ? ? ? ? ? > ? ? ? ? ? <el-button ? ? ? ? ? ? type="warning" ? ? ? ? ? ? size="medium" ? ? ? ? ? ? @click="operation(1)" ? ? ? ? ? ? v-if="adminType === 'manage'" ? ? ? ? ? ? >添加資訊</el-button ? ? ? ? ? > ? ? ? ? ? <el-button ? ? ? ? ? ? type="warning" ? ? ? ? ? ? size="medium" ? ? ? ? ? ? @click="operation(4)" ? ? ? ? ? ? v-if="adminType === 'manage'" ? ? ? ? ? ? >刪除</el-button ? ? ? ? ? > ? ? ? ? </el-form-item> ? ? ? </el-form> ? ? </div> ? ? <div class="room-cont"> ? ? ? <common-table ? ? ? ? :columnsData="columnsData" ? ? ? ? :tableData="tableData" ? ? ? ? v-loading="loading" ? ? ? ? @selectionChange="tableSelectChange" ? ? ? ></common-table> ? ? ? <pagenation ? ? ? ? :pageInfo="pager" ? ? ? ? @getNewPage="pageChange" ? ? ? ? v-if="tableData.length" ? ? ? ></pagenation> ? ? </div> ? </div> </template> <script> import CommonTable from '@/components/common/common-table'; import Pagenation from '@/components/common/pagenation'; import { timeFormat } from '@/utils/index'; import { mapState } from 'vuex'; export default { ? name: 'room-manage', ? components: { CommonTable, Pagenation }, ? data() { ? ? return { ? ? ? loading: false, //是否正在加載 ? ? ? param: { ? ? ? ? page: 1, ? ? ? ? pageSize: 10, ? ? ? ? columnCode: '', ? ? ? ? title: '', ? ? ? ? isTop: '', ? ? ? ? author: '' ? ? ? }, //參數(shù) ? ? ? pager: { ? ? ? ? total: 0, //總條數(shù) ? ? ? ? pageNum: 1, //當前頁碼 ? ? ? ? pageSize: 10 //每頁條數(shù) ? ? ? }, //分頁參數(shù) ? ? ? typeList: [ ? ? ? ? { label: '全部', value: '' }, ? ? ? ? { label: '圖片新聞', value: '01' }, ? ? ? ? { label: '通知公告', value: '02' }, ? ? ? ? { label: '工作動態(tài)', value: '03' }, ? ? ? ? { label: '教育資訊', value: '04' } ? ? ? ], ? ? ? chooseData: [], //選擇的列表數(shù)據(jù) ? ? ? columnsData: [ ? ? ? ? { ? ? ? ? ? label: '#', ? ? ? ? ? type: 'selection' ? ? ? ? }, ? ? ? ? { ? ? ? ? ? label: '序號', ? ? ? ? ? type: 'index' ? ? ? ? }, ? ? ? ? { ? ? ? ? ? label: '資訊標題', ? ? ? ? ? prop: 'title', ? ? ? ? ? width: 300, ? ? ? ? ? showOverflowTooltip: true ? ? ? ? }, ? ? ? ? { ? ? ? ? ? label: '資訊類型', ? ? ? ? ? prop: 'columnName' ? ? ? ? }, ? ? ? ? { ? ? ? ? ? label: '發(fā)布者', ? ? ? ? ? prop: 'author' ? ? ? ? }, ? ? ? ? { ? ? ? ? ? label: '發(fā)布時間', ? ? ? ? ? prop: 'createTime', ? ? ? ? ? formatter: row => { ? ? ? ? ? ? return row.createTime ? timeFormat(row.createTime) : '--'; ? ? ? ? ? } ? ? ? ? }, ? ? ? ? { ? ? ? ? ? label: '是否置頂', ? ? ? ? ? prop: 'isTop', ? ? ? ? ? formatter: row => { ? ? ? ? ? ? return row.isTop ? '否' : '是'; ? ? ? ? ? } ? ? ? ? }, ? ? ? ? { ? ? ? ? ? type: 'options', ? ? ? ? ? label: '操作', ? ? ? ? ? align: 'center', ? ? ? ? ? width: 150, ? ? ? ? ? render: (h, { row }) => { ? ? ? ? ? ? const checkBtn = h( ? ? ? ? ? ? ? 'a', ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? class: 'btn-option', ? ? ? ? ? ? ? ? on: { ? ? ? ? ? ? ? ? ? click: () => { ? ? ? ? ? ? ? ? ? ? this.operation(0, row); //預(yù)覽 ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? }, ? ? ? ? ? ? ? '預(yù)覽' ? ? ? ? ? ? ); ? ? ? ? ? ? const editBtn = h( ? ? ? ? ? ? ? 'a', ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? class: 'btn-option', ? ? ? ? ? ? ? ? on: { ? ? ? ? ? ? ? ? ? click: () => { ? ? ? ? ? ? ? ? ? ? this.operation(2, row); //修改 ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? }, ? ? ? ? ? ? ? '修改' ? ? ? ? ? ? ); ? ? ? ? ? ? const deleteBtn = h( ? ? ? ? ? ? ? 'a', ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? class: 'btn-option', ? ? ? ? ? ? ? ? on: { ? ? ? ? ? ? ? ? ? click: () => { ? ? ? ? ? ? ? ? ? ? this.operation(3, row); //刪除 ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? }, ? ? ? ? ? ? ? '刪除' ? ? ? ? ? ? ); ? ? ? ? ? ? let operationViews = []; ? ? ? ? ? ? operationViews.push(checkBtn); ? ? ? ? ? ? if (this.adminType === 'manage') { ? ? ? ? ? ? ? operationViews.push(editBtn); ? ? ? ? ? ? ? operationViews.push(deleteBtn); ? ? ? ? ? ? } ? ? ? ? ? ? return h( ? ? ? ? ? ? ? 'div', ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? class: 'table-opt-btns' ? ? ? ? ? ? ? }, ? ? ? ? ? ? ? operationViews ? ? ? ? ? ? ); ? ? ? ? ? } ? ? ? ? } ? ? ? ], //表頭數(shù)據(jù) ? ? ? tableData: [] //表格數(shù)據(jù) ? ? }; ? }, ? watch: { ? ? 'param.page'(n) { ? ? ? this.pager.pageNum = n; ? ? } ? }, ? computed: { ? ? ...mapState({ ? ? ? adminType: state => state.user.adminType ? ? }) ? }, ? mounted() { ? ? this.getList(); ? }, ? methods: { ? ? /** ? ? ?* 獲取列表 ? ? ?* @page {Number} 頁碼 ? ? ?*/ ? ? getList(page) { ? ? ? this.param.page = page || 1; ? ? ? this.loading = true; ? ? ? this.$api['course/getNewsList'](this.param) ? ? ? ? .then(res => { ? ? ? ? ? this.loading = false; ? ? ? ? ? this.tableData = res.list; ? ? ? ? ? this.pager.total = res.total; ? ? ? ? }) ? ? ? ? .catch(err => { ? ? ? ? ? this.loading = false; ? ? ? ? ? this.$toast(err, 3); ? ? ? ? }); ? ? }, ? ? /* 查詢 ?*/ ? ? handleSearchList() { ? ? ? this.getList(); ? ? }, ? ? /* 表格選擇 ?*/ ? ? tableSelectChange(val) { ? ? ? this.chooseData = val; ? ? }, ? ? /** ? ? ?* 表格操作 ? ? ?* @type {Number} 操作類型,0-查看,1-添加,2-修改,3-刪除,4-批量刪除 ? ? ?* @id {Number} 數(shù)據(jù)Id ? ? ?*/ ? ? operation(type, data) { ? ? ? if (type) { ? ? ? ? if (type === 1) { ? ? ? ? ? // 新增 ? ? ? ? ? this.$router.push('/newsEdit'); ? ? ? ? } else if (type === 2) { ? ? ? ? ? // 編輯 ? ? ? ? ? this.$router.push({ ? ? ? ? ? ? path: '/newsEdit', ? ? ? ? ? ? query: { ? ? ? ? ? ? ? newsId: data.id ? ? ? ? ? ? } ? ? ? ? ? }); ? ? ? ? } else if (type === 3) { ? ? ? ? ? // 刪除 ? ? ? ? ? this.del(data.id); ? ? ? ? } else { ? ? ? ? ? // 批量刪除 ? ? ? ? ? this.del('batch'); ? ? ? ? } ? ? ? } else { ? ? ? ? // 查看 ? ? ? ? this.$router.push({ ? ? ? ? ? path: '/newsDetail', ? ? ? ? ? query: { ? ? ? ? ? ? newsId: data.id, ? ? ? ? ? ? from: 'newsManage' ? ? ? ? ? } ? ? ? ? }); ? ? ? } ? ? }, ? ? /** ? ? ?* 刪除 ? ? ?* @data {Any} 數(shù)據(jù)Id/類型 ? ? ?*/ ? ? del(data) { ? ? ? let ids = [data]; ? ? ? if (data === 'batch') { ? ? ? ? if (this.chooseData.length) { ? ? ? ? ? ids = this.chooseData.map(cur => cur.id); ? ? ? ? } else { ? ? ? ? ? this.$toast('至少選擇一條記錄!', 2); ? ? ? ? ? return false; ? ? ? ? } ? ? ? } ? ? ? this.$confirm( ? ? ? ? '此操作將刪除' + ? ? ? ? ? (data !== 'batch' ? '該條' : '已選擇的') + ? ? ? ? ? '資訊, 是否繼續(xù)?', ? ? ? ? '提示', ? ? ? ? { ? ? ? ? ? confirmButtonText: '確定', ? ? ? ? ? cancelButtonText: '取消', ? ? ? ? ? type: 'warning' ? ? ? ? } ? ? ? ) ? ? ? ? .then(() => { ? ? ? ? ? this.$api['course/deleteNews']({ ? ? ? ? ? ? ids ? ? ? ? ? }) ? ? ? ? ? ? .then(res => { ? ? ? ? ? ? ? this.$message.success('刪除成功'); ? ? ? ? ? ? ? this.getList(); ? ? ? ? ? ? }) ? ? ? ? ? ? .catch(err => { ? ? ? ? ? ? ? this.$message.error(err); ? ? ? ? ? ? }); ? ? ? ? }) ? ? ? ? .catch(err => {}); ? ? }, ? ? /** ? ? ?* 翻頁 ? ? ?* @data {Number} 頁碼 ? ? ?*/ ? ? pageChange(data) { ? ? ? this.getList(data); ? ? } ? } }; </script> <style scoped lang="less"> .search-form { ? text-align: left; ? margin-top: 20px; } .room-cont { ? /deep/.el-table .el-table__row td .cell { ? ? font-size: 12px; ? } ? /deep/.el-table .el-table__row td:first-child .cell { ? ? font-size: 14px; ? } } </style>
5.vue全局過濾函數(shù)
!切記一定要在最外層的main.js或者是index.js里面 引入該filter.js文件
例如:將日期時間戳轉(zhuǎn)化為字符串時間,
{{ item.startTime | timeFormat('yyyy-MM-dd HH:mm') }} - {{ item.endTime | timeFormat('HH:mm') }} /** @format */ import Vue from 'vue'; /** ?* 時間戳轉(zhuǎn)日期格式 ?* @param data {number} 時間戳 ?* @param format {string} 時間格式[完整格式:yyyy-MM-dd HH:mm:ss,默認yyyy-MM-dd] ?* @param implementText {string} 缺省文字 ?*/ const timeFormat = function(data, format, implementText) { ? if (data === null || data === '' || data === undefined) { ? ? return implementText || ''; ? } ? format = format || 'yyyy-MM-dd'; ? let week = [ ? ? '星期日', ? ? '星期一', ? ? '星期二', ? ? '星期三', ? ? '星期四', ? ? '星期五', ? ? '星期六' ? ]; ? let date = new Date(data); ? let o = { ? ? 'M+': date.getMonth() + 1, ? ? 'd+': date.getDate(), ? ? 'h+': date.getHours() % 12, ? ? 'H+': date.getHours(), ? ? 'm+': date.getMinutes(), ? ? 's+': date.getSeconds(), ? ? 'q+': Math.floor((date.getMonth() + 3) / 3), ? ? 'S+': date.getMilliseconds(), ? ? 'W+': week[date.getDay()] ? }; ? if (/(y+)/.test(format)) ? ? format = format.replace( ? ? ? RegExp.$1, ? ? ? (date.getFullYear() + '').substr(4 - RegExp.$1.length) ? ? ); ? for (let k in o) ? ? if (new RegExp('(' + k + ')').test(format)) ? ? ? format = format.replace( ? ? ? ? RegExp.$1, ? ? ? ? RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length) ? ? ? ); ? return format; }; Vue.filter('timeFormat', timeFormat); /** ?* 年級code轉(zhuǎn)年級名稱 ?* @param data 數(shù)值 ?* @param implementText 缺省文案 ?*/ Vue.filter('revealGradeName', function(data, implementText) { ? if (data) { ? ? const gradeList = JSON.parse(sessionStorage.getItem('staticGrades')); ? ? return gradeList.filter(cur => cur.id === data)[0].name || ''; ? } else { ? ? return implementText || ''; ? } }); /** ?* 學(xué)段code轉(zhuǎn)學(xué)段名稱 ?* @param data 數(shù)值 ?* @param implementText 缺省文案 ?*/ Vue.filter('revealPhaseName', function(data, implementText) { ? return data ? ? ? { ? ? ? ? '03': '小學(xué)', ? ? ? ? '04': '初中', ? ? ? ? '05': '高中' ? ? ? }[data] ? ? : implementText || ''; }); /** ?* 學(xué)科code轉(zhuǎn)學(xué)科名稱 ?* @param data 數(shù)值 ?* @param implementText 缺省文案 ?*/ Vue.filter('revealSubjectName', function(data, implementText) { ? if (data) { ? ? const subjectList = JSON.parse(sessionStorage.getItem('staticSubjects')); ? ? return subjectList.filter(cur => cur.id === data)[0].name || ''; ? } else { ? ? return implementText || ''; ? } }); /** ?* 保留小數(shù)位 ?* @param data 數(shù)值 ?* @param len 保留的位數(shù) ?*/ Vue.filter('toFixed', function(data, len) { ? if (data) { ? ? typeof data === 'string' ? (data = Number(data)) : null; ? ? return data ? data.toFixed(len || 2) : data; ? } else { ? ? return 0; ? } }); Vue.prototype.$timeFormat = timeFormat;
6.vue的utils.js工具類常用方法
切記一定要在最外層的main.js或者是index.js里面 引入該utils.js文件
例如:淺拷貝 ,深拷貝,數(shù)據(jù)處理 等方法,
/** ?* 將秒數(shù)轉(zhuǎn)為時間格式 ?* ?* @format ?* @param data {number} 時間戳 ?* @param format {string} 時間格式[完整格式:yyyy-MM-dd HH:mm:ss,默認yyyy-MM-dd] ?* @param implementText {string} 缺省文字 ?*/ export function timeFormat(data, format, implementText) { ? if (data === null || data === '' || data === undefined) { ? ? return implementText || ''; ? } ? format = format || 'yyyy-MM-dd'; ? let week = [ ? ? '星期日', ? ? '星期一', ? ? '星期二', ? ? '星期三', ? ? '星期四', ? ? '星期五', ? ? '星期六' ? ]; ? let date = new Date(data); ? let o = { ? ? 'M+': date.getMonth() + 1, ? ? 'd+': date.getDate(), ? ? 'h+': date.getHours() % 12, ? ? 'H+': date.getHours(), ? ? 'm+': date.getMinutes(), ? ? 's+': date.getSeconds(), ? ? 'q+': Math.floor((date.getMonth() + 3) / 3), ? ? 'S+': date.getMilliseconds(), ? ? 'W+': week[date.getDay()] ? }; ? if (/(y+)/.test(format)) ? ? format = format.replace( ? ? ? RegExp.$1, ? ? ? (date.getFullYear() + '').substr(4 - RegExp.$1.length) ? ? ); ? for (let k in o) ? ? if (new RegExp('(' + k + ')').test(format)) ? ? ? format = format.replace( ? ? ? ? RegExp.$1, ? ? ? ? RegExp.$1.length === 1 ? o[k] : ('00' + o[k]).substr(('' + o[k]).length) ? ? ? ); ? return format; } /** ?* 將字符串時間轉(zhuǎn)換為時間戳 ?* @param {string} date ?*/ export function getDateTime(date) { ? let timestamp = ''; ? if (date) { ? ? date = date.substring(0, 19); ? ? date = date.replace(/-/g, '/'); //必須把日期'-'轉(zhuǎn)為'/' ? ? timestamp = new Date(date).getTime(); ? } ? return timestamp; } /** ?* 獲取年-月-日 ?* @data {Any} 時間戳 ?*/ export function getDates(data) { ? let timeObj = {}; ? data = new Date(data); ? let y = data.getFullYear(); ? let m = ? ? data.getMonth() + 1 < 10 ? ? ? ? '0' + (data.getMonth() + 1) ? ? ? : data.getMonth() + 1; ? let d = data.getDate() < 10 ? '0' + data.getDate() : data.getDate(); ? let w = data.getDay(); ? switch (w) { ? ? case 1: ? ? ? w = '星期一'; ? ? ? break; ? ? case 2: ? ? ? w = '星期二'; ? ? ? break; ? ? case 3: ? ? ? w = '星期三'; ? ? ? break; ? ? case 4: ? ? ? w = '星期四'; ? ? ? break; ? ? case 5: ? ? ? w = '星期五'; ? ? ? break; ? ? case 6: ? ? ? w = '星期六'; ? ? ? break; ? ? case 7: ? ? ? w = '星期日'; ? ? ? break; ? } ? let h = data.getHours() < 10 ? '0' + data.getHours() : data.getHours(); ? let mi = data.getMinutes() < 10 ? '0' + data.getMinutes() : data.getMinutes(); ? let s = data.getSeconds() < 10 ? '0' + data.getSeconds() : data.getSeconds(); ? timeObj = { ? ? year: y + '', ? ? month: m + '', ? ? day: d + '', ? ? week: w + '', ? ? hour: h + '', ? ? minute: mi + '', ? ? second: s + '' ? }; ? return timeObj; } /** ?* 異常處理 ?* @param {boolean} condition ?* @param {string} msg ?*/ export function assert(condition, msg) { ? if (!condition) throw new Error(`[Apior] ${msg}`); } /** ?* URL編碼; ?* @param {參數(shù)} param ?*/ export function toParams(param) { ? let result = ''; ? for (let name in param) { ? ? if (typeof param[name] != 'function') { ? ? ? if (param[name] === null) { ? ? ? ? result += '&' + name + '='; ? ? ? } else { ? ? ? ? result += '&' + name + '=' + encodeURI(param[name]); ? ? ? } ? ? } ? } ? return result.substring(1); } /** ?* 防抖函數(shù) ?* @param fn 高頻函數(shù) ?* @param wait 等待時間 ?* @returns {Function} ?*/ export function debounce(fn, wait) { ? let context = this, ? ? args = arguments, ? ? timer = null; ? return function() { ? ? context = this; ? ? args = arguments; ? ? clearTimeout(timer); ? ? timer = setTimeout(function() { ? ? ? fn.apply(context, args); ? ? }, wait || 250); ? }; } /** ?* 樹形數(shù)據(jù)轉(zhuǎn)換 ?* @param {*} data ?* @param {*} id ?* @param {*} pid ?*/ export function treeDataTranslate(data) { ? // 刪除 所有 children,以防止多次調(diào)用 ? data.forEach(function(item) { ? ? delete item.children; ? }); ? // 將數(shù)據(jù)存儲為 以 id 為 KEY 的 map 索引數(shù)據(jù)列 ? var map = {}; ? data.forEach(function(item) { ? ? map[item.id] = item; ? }); ? // ? ? ? ?console.log(map); ? var val = []; ? data.forEach(function(item) { ? ? // 以當前遍歷項,的pid,去map對象中找到索引的id ? ? var parent = map[item.pid]; ? ? // 好繞啊,如果找到索引,那么說明此項不在頂級當中,那么需要把此項添加到,他對應(yīng)的父級中 ? ? if (parent) { ? ? ? (parent.children || (parent.children = [])).push(item); ? ? } else { ? ? ? //如果沒有在map中找到對應(yīng)的索引ID,那么直接把 當前的item添加到 val結(jié)果集中,作為頂級 ? ? ? val.push(item); ? ? } ? }); ? return val; } /** ?* 對象深拷貝 ?* @param ?obj 對象 ?*/ export function cloneObj(obj) { ? let str; ? let newObj = obj.constructor === Array ? [] : {}; ? if ( ? ? Object.prototype.toString.call(obj) !== '[object Object]' && ? ? Object.prototype.toString.call(obj) !== '[object Array]' ? ) { ? ? return; ? } else if (window.JSON) { ? ? str = JSON.stringify(obj); // 系列化對象 ? ? newObj = JSON.parse(str); // 還原 ? } else { ? ? for (let i in obj) { ? ? ? newObj[i] = typeof obj[i] === 'object' ? this.cloneObj(obj[i]) : obj[i]; ? ? } ? } ? return newObj; } /** ?* @function deepCopy 淺深拷貝 ?* @param ?{type} obj {description} ?* @return {type} {description} ?*/ export function deepCopy(obj) { ? return JSON.parse(JSON.stringify(obj)); } /** ?* 設(shè)置本地localStorage ?* @name {String} 數(shù)據(jù)對象的KEY ?* @data {all} 對應(yīng)key的數(shù)據(jù) ?*/ export function setStorage(name, data) { ? let storage = window.localStorage; ? storage.setItem(name, JSON.stringify(data)); } /** ?* 拿到本地localStorage ?* @name {String} 數(shù)據(jù)對象的KEY ?*/ export function getStorage(name) { ? let storage = window.localStorage; ? let data = JSON.parse(storage.getItem(name)); ? return data; } /** ?* 設(shè)置本地sessionStorage ?* @name {String} 數(shù)據(jù)對象的KEY ?* @data {all} 對應(yīng)key的數(shù)據(jù) ?*/ export function setSessionStorage(name, data) { ? let storage = window.sessionStorage; ? storage.setItem(name, JSON.stringify(data)); } /** ?* 拿到本地sessionStorage ?* @name {String} 數(shù)據(jù)對象的KEY ?*/ export function getSessionStorage(name) { ? let storage = window.sessionStorage; ? let data = JSON.parse(storage.getItem(name)); ? return data; } /** ?* 取出對象中制定屬性返回新對象 ?* @obj {Object} 數(shù)據(jù)對象的KEY ?* @keys {Array} 數(shù)據(jù)對象的KEY ?*/ export function certainProperty(obj, keys) { ? return keys.reduce((result, key) => { ? ? if (obj.hasOwnProperty(key)) { ? ? ? result[key] = obj[key]; ? ? } ? ? return result; ? }, {}); } /*遞歸 根據(jù)子元素找到父級元素 */ export function getParent(data2, nodeId2) { var arrRes = []; if (data2.length == 0) { if (nodeId2) { arrRes.unshift(data2); } return arrRes; } let rev = (data, nodeId) => { for (var i = 0, length = data.length; i < length; i++) { let node = data[i]; if (node.id == nodeId) { arrRes.unshift(node); rev(data2, node.pid); break; } else { if (node.child) { rev(node.child, nodeId); } } } return arrRes; }; arrRes = rev(data2, nodeId2); return arrRes; }
7.切記在vue的main.js或在最外層的index.js中
需要引入其中的一些js文件,現(xiàn)貼出main.js中的代碼,提供參考。
/** @format */ import 'babel-polyfill'; import 'element-ui/lib/theme-chalk/index.css'; import '@/assets/styles/reset.less'; import '@/assets/styles/common.less'; import '@/assets/styles/theme-reset.less'; import Vue from 'vue'; import App from './App'; import ElementUI from 'element-ui'; Vue.use(ElementUI); /* 導(dǎo)入視頻插件 */ import VideoPlayer from 'vue-video-player'; Vue.use(VideoPlayer); // 導(dǎo)入插件 import plugin from '@/plugins'; import router from '@/router'; import store from '@/store'; /* 導(dǎo)入公用方法 */ import '@/utils/prototypes'; import '@/utils/filters'; import '@/utils/directives'; import VueJsonp from 'vue-jsonp'; Vue.use(VueJsonp); Vue.config.productionTip = false; Vue.use(plugin); new Vue({ ? el: '#app', ? store, ? router, ? components: { App }, ? template: '<App/>' });
總結(jié)
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
vue-router 源碼實現(xiàn)前端路由的兩種方式
這篇文章主要介紹了vue-router 源碼實現(xiàn)前端路由的兩種方式,主要介紹Hash 路由和History 路由,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-07-07vue3+vue-cli4中使用svg的方式詳解(親測可用)
最近在做個vue的項目,從各種github上的開源庫上借鑒開發(fā)方法,給大家分享下,這篇文章主要給大家介紹了關(guān)于vue3+vue-cli4中使用svg的相關(guān)資料,需要的朋友可以參考下2022-08-08淺談在vue中用webpack打包之后運行文件的問題以及相關(guān)配置方法
下面小編就為大家分享一篇淺談在vue中用webpack打包之后運行文件的問題以及相關(guān)配置方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-02-02