作者:爱飞扬无限_316 | 来源:互联网 | 2023-08-15 19:04
废话不多说,咱直接上代码!这里以laravel,vue,vue-apollo为例这里涉及到其他插件的配置使用,请参考链接:vue:https:github.comvuejsvuev
废话不多说,咱直接上代码!这里以laravel
, vue
, vue-apollo
为例
这里涉及到其他插件的配置使用,请参考链接:
- vue:https://github.com/vuejs/vue
- vue-apollo: https://github.com/Akryum/vue-apollo
- vee-validate:https://github.com/baianat/vee-validate
namespace YouNamespace;
use GraphQL\Type\Definition\Type;
use Folklore\GraphQL\Support\Query;
use App\Contracts\UserInterface;
use App\User;
class UserFieldQuery extends Query
{
protected $attributes = [
'name' => 'User field Query'
];
public function type()
{
return Type::boolean();
}
public function args()
{
return [
'field' => [
'type' => Type::nonNull(Type::string()),
],
'value' => [
'type' => Type::nonNull(Type::string()),
]
];
}
public function resolve($root, $args)
{
[$field, $value] = array_values($args);
// 定义合法的字段验证。
switch ($field) {
case 'mobile_phone':
return User::findByMobilePhone($value) instanceof UserInterface;
break;
case 'nikename':
return User::findByNikename($value) instanceof UserInterface;
break;
}
return false;
}
}
添加查询到配置文件 config/graphql.php
'schemas' => [
'default' => [
'query' => [
'user_field_exist' => 'YouNamespace\UserFieldQuery'
],
// ...
]
]
import gql from 'graphql-tag';
import graphqlClient from '@/graphql';
class AsynFieldRemoteValidator {
static async queryUserFieldUnique(field, value) {
const {data} = await graphqlClient.query({
query: gql`query UserFieldQuery($field: String!, $value: String!){
user_field_exist(field: $field, value: $value)
}`,
variables: {
field: field,
value: value
}
});
return data;
}
}
export default AsynFieldRemoteValidator;
你的vue组件。在created()
方法定义
import AsynFieldRemoteValidator from '@/support/asyn-field-remote-validator';
this.$validator.extend('unique_user_field', {
getMessage(field, params, data) {
return this.$t('core.message.unique_field', {field});
},
async validate(value, args) {
const field = args[0];
let result = value
// 这里判断验证手机号码时处理手机号码格式。使用`libphonenumber-js` 参考:https://github.com/catamphetamine/libphonenumber-js, 这里不多介绍`libphonenumber-js`使用
if (field === 'mobile_phone') {
result = parseIncompletePhoneNumber(value, local.alias.toUpperCase());
}
const {user_field_exist} = await AsynFieldRemoteValidator.queryUserFieldUnique(field, result);
return {
valid: user_field_exist === false,
data: {
field: result
}
};
}
})
type="tel"
v-model="mobile_phone"
:placeholder="188 **** ****"
:state="validateState('mobile_phone')"
:data-vv-as="手机号码"
name="mobile_phone"
v-validate="'required|mobile_pohone_format|unique_user_field:mobile_phone'"
文章写得非常粗暴,大神多多指教!
laravel
vue
graphql
vue-apollo