我正在尝试从 require
d javascript 文件访问我的 Vue 元素,但到目前为止我失败了...我想使用 element-ui 的 el-form-item
组件的外部规则验证器。也许我的逻辑是错误的,但这种方式应该也有效(我猜)
Vue@2.5.13
element-ui@2.0.11
npm@5.6.0
Vue.use(...)
我尝试了 Vue.use(...)
我的 javascript 文件。
const MyPlugin = {
install(Vue, options) {
Vue.prototype.usernameValidator = function (rule, value, callback) {
console.log(Vue);
console.log(this);
// ...
我的控制台输出:
console.log(Vue);
ƒ Vue$3(options) {
if ("development" !== 'production' &&
!(this instanceof Vue$3)
) {
warn('Vue is a constructor and should be called with thenew
keyword');
}
this._init(options);
}
console.log(this);
{"required":true,"field":"username","fullField":"username","type":"string"...}
创建前
module.exports = function (rule, value, callback) {
console.log(this)
// ...
});
console.log(this);
{"required":true,"field":"username","fullField":"username","type":"string"...}
正如我所说,我的逻辑可能是错误的,但我很好奇我可以制作这样的方法吗?
问候
更新
我在 register.blade.php
中调用它
<el-form-item label="Username" prop="username" :rules="[{required:true, validator: usernameValidator, trigger:'blur,change'}]">
<el-input v-model="form.username" name="username"></el-input>
</el-form-item>
在app.js
;
Vue.use(require('./plugins/usernameValidator'));
// ...
window.app = new Vue({
// ...
});
最佳答案
您在哪里需要
元素?我将详细说明我通常如何使用您的示例创建插件。
定义一个插件:
// my-plugin.js
import {FormItem} from 'element-ui'
const MyPlugin = {
install(Vue, options) {
Vue.prototype.usernameValidator = function (rule, value, callback) {
// use FormItem's validator
然后通过Vue.use
注册插件:
// app.js
import MyPlugin from 'my-plugin'
// or require
const MyPlugin = require('my-plugin')
Vue.use(MyPlugin)
稍后在组件中,调用插件中定义的 usernameValidator
方法:
<template>
<input name="username" v-model="username" :class="isValidUsername ? 'borderGreen' : 'borderRed'" />
<div>{{ usernameFeedback }}</div>
</template>
export default {
beforeCreate () {
// what would you validate in here?
// this.usernameValidator(rule, value, callback)
},
data () {
return {
username: null,
usernameFeedback: null
}
},
computed: {
isValidUsername () {
// assuming the validator returns a boolean, valid/invalid
return this.usernameValidator(rule, this.username, this.validationCallback)
}
},
methods: {
validationCallback (feedback) {
this.usernameFeedback = feedback
}
}
}
如果您有一个如何需要
组件的示例,我可以更新我的答案,但实际上您可以使用this
访问组件中的插件方法。
关于javascript - 从导入的文件访问 vue,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48530465/