项目结构如下:
service.js代码如下:
const getUsers = function() {
let ret = '[{"account":"zhengzizhi","password":"123456"}]';
return JSON.parse(ret);
};
export default {
getUsers // export的作用是导出函数,getUsers是vue调用getUsers()函数的接口
}
index/index.vue代码如下:
<template>
<view class="content">
<view class="text-area">
<text class="title">this is a testing</text>
</view>
</view>
</template>
<script>
import service from '../../service.js';
const password = '123456';
export default {
data() {
return {
}
},
onLoad() {
console.log(this.test());
},
methods: {
test:function(){
var result = false;
const info = service.getUsers();
result = info.some(function(user){
console.log(user);
return password === user.password;
});
return result;
}
}
}
</script>
再看看,javascript函数直接定义在vue页面里声明格式,
我们不需要再为javascript函数单独创建一个js文件,
这种方式不需要使用关键字import导入js文件,
我们可以直接使用export导出接口名称调用函数方法,
这种方式虽然少见,但对于阅读代码帮助很大,代码如下:
<template>
<view class="content">
<view class="text-area">
<text class="title">this is a testing</text>
</view>
</view>
</template>
<script>
const getUsers = function() {
let ret = '[{"account":"zhengzizhi","password":"123456"}]';
return JSON.parse(ret);//字符串格式的json数组被转换成数组
};
export {
getUsers // export的作用是导出函数,getUsers是vue调用getUsers()函数的接口
}
const password = '123456';
export default {
data() {
return {
}
},
onLoad() {
console.log(this.test());
},
methods: {
test:function(){
var result = false;
// info是一个数组 JavaScript数组 Array的some()方法,它的输入参数通常是一个匿名函数
const info = getUsers();
result = info.some(function(user){
console.log(user);
return password === user.password;
});
return result;
}
}
}
</script>
<style>
.content {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.text-area {
display: flex;
justify-content: center;
}
.title {
font-size: 36rpx;
color: #8f8f94;
background-color: #4CD964;
}
</style>