【问题标题】:Vue to validate form field using methodVue使用方法验证表单字段
【发布时间】:2019-08-02 12:16:10
【问题描述】:

首先,我是 Vue 的新手,所以请多多包涵。 我正在研究由其他人编写的代码库。该应用程序非常简单,只是一个收集数据的表格。其中一个字段是邮政编码字段,并具有以下验证:

postcodeRules: [v => !!v || "Please enter your postcode"]

如果我理解正确,它所做的就是针对空字段进行验证。我想添加一个方法被调用来验证这个字段,例如:

postcodeRules: [v => !!v || "Please enter your postcode", v => this.checkPostcode(v) || "Postcode not valid"]

checkPostcode() 会调用外部 API,但我收到错误:TypeError: Cannot read property 'checkPostcode' of undefined

我也试过了

postcodeRules: [v => !!v || "Please enter your postcode", v => checkPostcode(v) || "Postcode not valid"]

这是我的全部代码:https://gist.github.com/WagnerMatos/f884e97fe47c4553e6e5aaf3ebbec792

知道如何让它工作吗?

提前致谢!

编辑 这是模板代码:https://gist.github.com/WagnerMatos/c2e45bdf00db06f98a109e6313dd35a8

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    您应该将 checkPostcode() 移动到组件 methods 以使其可以从组件上下文中访问,而不是将其放在 data 键下。请参阅Vue 文档here

    <script>
        export default {
             methods: {
                 checkPostcode(postcopde) {
                     console.log(postcopde);
                 }
            }
        }
    </script>
    

    【讨论】:

      【解决方案2】:

      问题在于箭头函数中 this 的上下文。您可以尝试这种解决方法,它不是美,而是有效。您可以使用内部函数在其中运行逻辑。

      data: () => ({
          postcode: 0,
          postcodeRules: [val => {
              if(!val) 
                return "Please enter your postcode"
      
              if(!checkPostcode(val)) {
                return "Postcode not serviced."
              }
              else {
                return true
              }
      
              function checkPostcode(postcode) {
                console.log(postcode)
                return false
              }
          }]
      })
      

      【讨论】:

      • 和@Kenneth 我已经尝试过了,但我仍然得到同样的错误:TypeError: Cannot read property 'checkPostcode' of undefined
      • @WagnerMatosUK 是的,但是这个组件包含 html 部分。
      • 刚刚添加。谢谢!
      • 刚刚添加了它的html部分@Sousuke
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      • 2017-05-18
      • 2011-01-29
      • 2021-01-20
      • 2016-04-29
      相关资源
      最近更新 更多