【问题标题】:How to use Mixin in main.js in Vuejs?如何在 Vuejs 的 main.js 中使用 Mixin?
【发布时间】:2020-10-17 15:43:18
【问题描述】:

我正在尝试使用来自 mixin 的全局信息。我打算访问组件中的getNow 计算属性,但它似乎是undefined

main.js:

Vue.mixin({
    data: function() {
        return {
          chainBoxURL: "http://172.22.220.197:18004/jsonrpc"
        }
    },
    computed: {
        getNow() {
          const today = new Date();
          const date = today.getFullYear() + '-' + (today.getMonth() + 1) + '-' + today.getDate();
          const time = today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds();
          const dateTime = date + ' ' + time;
          return dateTime;
        }
    }
})

组件:

methods: {
    getChainAddress(form) {
        if (form.password == form.password_again && form.password != '') {
            console.log(this.getNoW)
        }
    }
}

【问题讨论】:

  • 发生了什么?您是否收到错误消息?控制台日志的输出是什么?你在哪里包含组件中的mixin?这些信息不足以准确确定您需要什么。
  • 感谢收听。我需要在 client.vue 组件中使用 getNoW 方法。但是它显示为未定义。
  • prop 定义为getNow,但您的组件尝试访问getNoW(带大写W)。

标签: vue.js vuejs2 vue-mixin


【解决方案1】:

当您尝试访问getNow 时,似乎有一个错字,有一个W 而不是w

旁注,

  1. 您可以使用template strings 让生活更轻松
const today = new Date();
const date = `${today.getFullYear()}-${(today.getMonth() + 1)}-${today.getDate()}`;
const time = `${today.getHours()}:${today.getMinutes()}:${today.getSeconds()}`;
const dateTime = `${date} ${time}`;
  1. 您可以在if 语句中翻转您的条件,因为如果&& 的情况下第一个为假,JS 将不会评估第二个条件
if (form.password != '' && form.password == form.password_again) {
  console.log(this.getNoW)
}

【讨论】:

    【解决方案2】:

    mixin 中的计算 prop 定义为:getNow(),但你在组件中将其拼写为 getNoW()

    或者你可能忘记在组件中包含 mixin。

    【讨论】:

      猜你喜欢
      • 2019-02-16
      • 2017-06-20
      • 2017-01-18
      • 2018-05-02
      • 2020-05-06
      • 2021-03-04
      • 2019-04-16
      • 2016-07-29
      • 2019-03-08
      相关资源
      最近更新 更多