[英]Access vue from imported file
我正在嘗試從require
d javascript文件訪問我的Vue元素但是我到目前為止失敗了......我想從外面獲取element-ui的el-form-item
組件的規則驗證器。 也許我的邏輯是錯的,但這種方式也應該有效( 我猜 )
Vue@2.5.13
element-ui@2.0.11
npm@5.6.0
我試過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(選項){
if(“development”!=='production'&&
!(這個Vue $ 3的實例)
){
warn('Vue是一個構造函數,應該用new
關鍵字調用');
}
this._init(選項);
}
的console.log(本);
{ “要求”:真正的 “現場”: “用戶名”, “fullField”: “用戶名”, “類型”: “串” ...}
module.exports = function (rule, value, callback) {
console.log(this)
// ...
});
的console.log(本);
{ “要求”:真正的 “現場”: “用戶名”, “fullField”: “用戶名”, “類型”: “串” ...}
正如我所說,我的邏輯可能有誤,但我只是好奇,我可以制作這樣的方法嗎?
問候
我在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({
// ...
});
你require
在哪里元素? 我將詳細介紹我如何使用您的示例創建插件。
定義一個插件:
// 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
}
}
}
如果你有一個你怎么一個例子require
一個組成部分,我可以更新我的答案,但因為它是你可以在一個組件使用訪問插件方法this
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.