总结:具体的取值规则
- data数据里面,key相同取组件的value值
- created方法,先执行混入对象的created方法,在执行组件的created方法
- method方法里面,同名的函数,只执行组件对象的函数,混入对象的同名函数被覆盖了。
- 混入对象无法调用组件对象的同名函数,组件对象可以调用混入对象methods里面定义的函数。
混入的方式
混入的方式一:单页面引入混入
首先创建一个 mixin 文件夹,然后再在里面创建一个mixin.js文件
然后再创建混入对象:
let mixin = {
data(){
return{
str:'你好'
}
},
created() {
console.log("我是混入的生命周期函数")
},
methods: {
showToast(){
alert("我是混入中的方法啊!")
}
},
}
// 记住,最后一定要导出
export default mixin
在组件中使用混入:
import mixin from '../mixin/mixin.js' // 首先引入这个混入对象
export default {
mixins:[mixin], // 然后注册你引入的这个混入对象
}
混入方式二、全局混入:
创建混入对象的方式还是和上面方法一样,我这里就直接引入了;
在main.js中引入混入对象并全局注册
import mixin from './mixin/mixin'
Vue.mixin(mixin);
常用的混入方法
export default {
data() {
return {
webImg: this.$store.state.imgRoot, //网络图片前缀
_lastTime: null, //上次点击时间
isOffLine: false, //是否断网了
};
},
filters: {
priceFilter(v) {
if (v) {
let price = String(v)
if (price.indexOf(".") > 0) {
price = price.replace(/0+?$/, ""); //去掉多余的0
price = price.replace(/[.]$/, ""); //如最后一位是.则去掉
}
return price
} else {
return v
}
},
createdAtFilter(v) {
let len = v.length - 3
return v.substring(0, len)
},
},
methods: {
//http 网络加载
// post(params) {
// console.log(this.$http)
// return this.$http.post(params);
// },
// get(params) {
// return this.$http.get(params);
// },
// 上传图片列表
upPicList(fileType, count, fun) {
uni.chooseImage({
count: count, //默认9
sizeType: ['original'], //可以指定是原图还是压缩图,默认二者都有
sourceType: ['album', 'camera'], //从相册选择
success: res => {
console.log(JSON.stringify(res))
uni.showLoading({
title: '上传中...'
})
var list = []
this.upFile(fileType, res.tempFilePaths, list, fun)
}
});
},
// 预览图片
showPic(list, index) {
var listnea = []
for (var i = 0; i < list.length; i++) {
listnea.push(list[i])
}
uni.previewImage({
urls: listnea,
current: index,
longPressActions: {
itemList: ['保存图片', ],
success: function(data) {},
fail: function(err) {}
}
});
},
//上传文件
upFile(fileType, paths, list, fun) {
this.$http.upLoad({
file: paths[list.length],
fileType
}).then(res => {
console.log(res)
if (res.code == 200) {
list.push(res.data)
if (paths.length == list.length) {
uni.hideLoading()
if (fun) {
fun(list)
}
} else {
this.upFile(fileType, paths, list, fun)
}
} else {
uni.hideLoading()
}
})
},
//上传视频
up_video(fileType, key, fun, funTask) {
let _this = this
uni.chooseVideo({
count: 1,
compressed: false,
sourceType: ['camera', 'album'],
success: function(res) {
console.log(res)
if (res.tempFilePath) {
let tempFilePaths = res.tempFilePath
_this.$http.upLoad({
file: tempFilePaths,
fileType
}, funTask).then(ras => {
if (ras.code == 200) {
if (fun) {
fun(ras.data)
}
} else {
this.toast(ras.msg)
}
})
}
}
});
},
//上传图片
up_img(fileType, fun, sourceType) {
let _this = this
uni.chooseImage({
count: 1, //默认9
sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图,默认二者都有
sourceType: sourceType ? sourceType : ['album', 'camera'], //从相册选择
success: res => {
if (res.tempFilePaths && res.tempFilePaths.length > 0) {
let tempFilePaths = res.tempFilePaths[0]
console.log(fileType);
_this.$http.upLoad({
file: tempFilePaths,
fileType
}).then(ras => {
if (ras.code == 200) {
if (fun) {
console.log(ras);
fun(ras.data)
}
} else {
this.toast(ras.msg)
}
})
}
}
});
},
//跳转
openPages(url) {
uni.navigateTo({
url: url
})
},
//跳转
openPagesRedirect(url) {
uni.redirectTo({
url: url
})
},
//跳转
openPagesReLaunch(url) {
uni.reLaunch({
url: url
})
},
//返回
navigateBack(delta) {
uni.navigateBack({
delta: delta ? delta : 1
})
},
//跳转 检测登录跳转
navigateToCheck(url) {
if (this.checkUserToLogin()) {
this.openUrl(url)
}
},
//打开地址
openUrl(url) {
console.log(url);
this.throttle(() => {
this.openPages(url);
});
},
//打开地址
openUrlRedirect(url) {
this.throttle(() => {
this.openPagesRedirect(url);
});
},
//检测是否登录
checkUserToLogin() {
if (!this.checkUser()) {
this.navToLogin()
}
return this.checkUser();
},
//检测是否登录
checkUserDialog() {
if (!this.checkUser()) {
uni.showModal({
title: '提示',
content: '您尚未登录,是否去登录!',
success: function(res) {
if (res.confirm) {
this.navToLogin()
}
}
})
}
return this.checkUser();
},
/**
* 如果没有登录 跳转登录
*/
navToLogin() {
// #ifdef APP-PLUS
uni.$emit('phoneLogin')
// #endif
// #ifndef APP-PLUS
this.openUrl('/pages/login/login')
// #endif
},
//检测是否登录
checkUser() {
if (!uni.getStorageSync('token')) {
return false
}
return true;
},
//保存用户token
saveToken(token) {
this.$store.commit('changeToken', token);
uni.$emit('bindPush')
},
//保存用户信息
saveUser(user) {
this.$store.commit('changeUserInfo', user);
},
//格式化时间
/**
* 人性化时间处理 传入时间戳
*/
formateTime1(timestamp) {
var mistiming = Math.round(new Date() / 1000) - timestamp / 1000;
var postfix = mistiming > 0 ? '前' : '后'
mistiming = Math.abs(mistiming)
var arrr = ['年', '个月', '星期', '天', '小时', '分钟', '秒'];
var arrn = [31536000, 2592000, 604800, 86400, 3600, 60, 1];
for (var i = 0; i < 7; i++) {
var inm = Math.floor(mistiming / arrn[i])
if (inm != 0) {
return inm + arrr[i] + postfix
}
}
},
dateFtt(fmt, date) { //author: meizz
var o = {
"M+": date.getMonth() + 1, //月份
"d+": date.getDate(), //日
"h+": date.getHours(), //小时
"m+": date.getMinutes(), //分
"s+": date.getSeconds(), //秒
"q+": Math.floor((date.getMonth() + 3) / 3), //季度
"S": date.getMilliseconds() //毫秒
};
if (/(y+)/.test(fmt))
fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
for (var 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;
},
/**
* 是否有网络
*/
getNetworkType() {
return new Promise((resolve, reject) => {
// #ifdef H5
resolve()
// #endif
// #ifdef MP-WEIXIN
uni.getNetworkType({
success: (res) => {
if (res.networkType != 'none') {
this.isOffLine = false
resolve()
} else {
this.isOffLine = true
reject()
}
},
fail: () => {
this.isOffLine = true
reject()
}
});
// #endif
})
},
/**
* 节流
*/
throttle(fn, gapTime) {
if (gapTime == null || gapTime == undefined) {
gapTime = 500
}
let _nowTime = +new Date()
if (_nowTime - this._lastTime > gapTime || !this._lastTime) {
fn()
this._lastTime = _nowTime
}
},
//警告提示
showModalTip(tip, title, fn) {
uni.showModal({
title: title ? title : '提示',
content: tip,
showCancel: false,
success(e) {
if (e.confirm) {
if (fn) {
fn()
}
}
}
})
},
//吐司
toast(title, duration, icon) {
if (title) {
uni.showToast({
title: title,
icon: icon ? icon : 'none',
duration: duration ? duration : 2000
})
}
},
upx2px(px) {
return uni.upx2px(px)
},
//格式化时间
/**
* 人性化时间处理 传入时间戳
*/
formateTime1(timestamp) {
var mistiming = Math.round(new Date() / 1000) - timestamp / 1000;
var postfix = mistiming > 0 ? '前' : '后'
mistiming = Math.abs(mistiming)
var arrr = ['年', '个月', '星期', '天', '小时', '分钟', '秒'];
var arrn = [31536000, 2592000, 604800, 86400, 3600, 60, 1];
for (var i = 0; i < 7; i++) {
var inm = Math.floor(mistiming / arrn[i])
if (inm != 0) {
return inm + arrr[i] + postfix
}
}
},
},
mounted() {
//console.log(this.$http)
},
}