【问题标题】:In Vue.js, how do I access a function within a single file component?在 Vue.js 中,如何访问单个文件组件中的函数?
【发布时间】:2019-01-19 06:18:05
【问题描述】:

在 Vue.js 中,我创建了一个名为 Password.vue 的单个文件组件,其中包含两个密码字段和相关检查。

首先,我在<template></template> 标记中定义了我的 HTML,这可以正常工作。

然后,我定义我的 JavaScript 代码如下:

<script>

    computed: {
        passwordsValid() {

           // Password checking code here
        }
    },

};
</script>

然后我有一个注册功能,它导入Password.vue

import PasswordComponent from "../components/Password.vue";

然后在我的signup.html 文件中,我有

<password-component></password-component>

使用实际的密码组件。

我的问题是,我的 passwordsValid 函数包含在 Password.vue 中,我无法从 signup.html 文件中访问它。

我该怎么做?换句话说,如何访问单个文件组件中的函数?

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    为 Password.vue 创建道具:

    props: {
      requestCheckPassword: Boolean,
    }
    

    添加手表:

    watch: {
      requestCheckPassword () {
        this.$emit('passwordResult', {isValid: this.passwordsValid})
        this.$emit('update:requestCheckPassword', false)
      }
    }
    

    然后在signup.html文件中:

    <password-component @passwordResult="methodFromMethodsSection" :request-check-password.sync="requestCheckPassword"></password-component>
    

    最后,在 signup.html 中添加:

    data () {
      return {
        requestCheckPassword: false
      }
    },
    methods: {
      methodFromMethodsSection ({ isValid }) {
        // your logic, you can access isValid
      }
    }
    

    如果你想得到密码检查结果,只需从数据中更改requestCheckPassword。例如:

    <button @click="requestCheckPassword = true">Click me</button>
    

    【讨论】:

      猜你喜欢
      • 2016-09-05
      • 2019-02-23
      • 1970-01-01
      • 2016-12-18
      • 2016-08-09
      • 2017-04-14
      • 2017-02-06
      • 2018-09-04
      • 1970-01-01
      相关资源
      最近更新 更多