簡體   English   中英

從導入的文件訪問vue

[英]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(...)

我試過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”: “用戶名”, “類型”: “串” ...}


beforeCreate

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM