【问题标题】:Dynamically Accessing Vue Data动态访问 Vue 数据
【发布时间】:2016-10-13 09:15:19
【问题描述】:

我目前正在为我正在使用 Node.js 和 Vue.js 进行的个人项目构建登录页面,但在 vue 实例之间访问数据时遇到了一些问题。

我目前正在使用它,如果布尔数据值为 true,则文本输入框将分配一个 error 类。我有两个单独的 Vue 用于字段,用户名输入和电子邮件输入:

var user = new Vue({

    el: '#usr-field',
    data: {
        hasError: messages.inUse.show || messages.tooShort.show
    }

});



var email = new Vue({

    el: '#email-field', 
    data: {
        hasError: messages.idLength.show
    }

});

就在同一个文件中,Vuejs 用于显示错误消息(如果有的话):

var messages = new Vue({

    el: '#errors', 
    data: {
        showErrors: false, 
        inUse: {
            show: false,
            text: 'The username you chose is already in use'
        }, 
        tooShort: {
            show: false,
            text: 'The username you chose is too short (4 character minimum)'
        }, 
        idLength: {
            show: false,
            text: 'The email you provided does not match the standard 7 character format'
        }
    },
    methods: {
        resetErrors: function() {
            if (this.showErrors) {
                this.showErrors = false;
                this.idLength.show = false;
                this.inUse.show = false;
                this.tooShort.show = false;
            }
        },
    }

});

我目前尝试动态访问 messages Vue 值的方式除了在加载时不起作用。有没有办法让useremail Vue 的hasError 数据根据messages Vue 数据动态变化?

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    首先,只创建一个 Vue 实例。

    使用包含您的登录表单输入元素的元素。 例如。一个 id 为 login 的 div 包装器。

    new Vue({
      el: '#login', 
      data: {
          showErrors: false, 
          inUse: {
              show: false,
              text: 'The username you chose is already in use'
          }, 
          tooShort: {
            show: false,
            text: 'The username you chose is too short (4 character minimum)'
          }, 
          idLength: {
            show: false,
            text: 'The email you provided does not match the standard 7 character format'
          }
      },
      methods: {
        resetErrors: function() {
            if (this.showErrors) {
                this.showErrors = false;
                this.idLength.show = false;
                this.inUse.show = false;
                this.tooShort.show = false;
            }
        },
      }
    });
    

    然后在您的 HTML 中,使用 v-bind:class 在您的输入中显示或隐藏您的类 error,如下所示:

    <input id="usr-field" :class="{'error': messages.inUse.show || messages.tooShort.show}" ...
    

    您的电子邮件字段的想法相同:

    <input id="email-field" :class="{'error': messages.idLength.show}" ...
    

    如果以后您觉得需要隔离逻辑,您可能需要研究组件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-08-03
      • 2017-10-17
      • 2015-11-21
      • 2018-02-05
      • 2019-08-12
      • 1970-01-01
      相关资源
      最近更新 更多