【问题标题】:Property or method "value" is not defined on the instance but referenced during render属性或方法“值”未在实例上定义,但在渲染期间被引用
【发布时间】:2020-03-06 02:32:26
【问题描述】:

我查看了其中一个答案并尝试应用它,但后来我意识到它不起作用,我尝试了很多方法,例如使用 Vuex 来计算我使用它之前的年份,但没有任何效果。

Generate Years from 1900 to current year with VueJS

属性或方法“值”未在实例上定义,但在渲染期间被引用。通过初始化该属性,确保此属性是反应性的,无论是在数据选项中,还是对于基于类的组件。请参阅:https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties

就像我说的,我尝试使用 Vuex 并尝试在 beforeCreate 钩子上调用它,但它不起作用。

<template>
          <md-field md-clearable>
                <label for="year">Year</label>
                <md-select v-model="year" name="year" id="year">
                    <md-option :v-for="value in values" value="value">
                        {{ value }}
                    </md-option>

                </md-select>
          </md-field>
</template>

<script>

export default {
  name: 'Component',
  data () {
     year: null
  },
  computed: {
  values () {
      const year = new Date().getFullYear()
      return Array.from({length: year - 1900}, (value, index) => 1901 + index)
    }
  }


}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss"  scoped>
</style>

我希望下拉列表具有年份值,而不是为空并给出错误消息。我也尝试重命名这些值,但它不必对此做任何事情。这是一个非常奇怪的错误。我很想知道它是否是由 vue.js 本身引起的。

【问题讨论】:

  • year 未定义,您在 v-model 中使用它
  • 我也尝试将其重命名为 myear,但没有成功。
  • 是的,你需要定义它。在data(){ return { myyear: null }});
  • 但这并不重要,因为我一开始就把“年”换成了“价值”。
  • 我不确定你的意思

标签: vue.js


【解决方案1】:

您的数据属性应该返回值:

data () {
  return {
    year: null
  }
},

而且你的 v-for 前面不应该有 :

  <option v-for="value in values" >
    {{ value }}
  </option>

修复这些,它应该可以工作。

【讨论】:

    【解决方案2】:

    上一个错误背后的原因很可能是你忘记在你的 Vue 应用程序的数据对象中定义 prop XXX:

    var application = new Vue({
        el: '#app',
        data: {
            // The prop XXX is not defined here, so add it ;)
        }
    });

    【讨论】:

      【解决方案3】:

      您的代码中有两个问题:

      1. 您没有正确使用数据属性。您应该像这样在数据中返回值:
      data () {
        return {
          year: null
        }
      }
      
      1. 您在 v-for 之前使用了 :,这是错误的,我认为这就是您面临问题的原因。只需删除 :

      希望对你有帮助!!

      【讨论】:

        【解决方案4】:

        您的代码中有两个错误。

        第一个是:

        <md-option v-for="(val,index) in values" :key="index" :value="val">
          {{ value }}
        </md-option>
        
        1. 您需要使value 属性具有反应性,以考虑来自v-for 循环的动态值。
        2. 在使用v-for 时始终使用:key 属性。
        3. : 不应作为 v-for 的前缀。
        4. 尽量使变量名与属性不同,以便更好地理解代码。

        第二个是:

        data () {
          return {
            year: null
          }
        },
        

        您在data() 对象中缺少return

        【讨论】:

          猜你喜欢
          • 2018-09-17
          • 2022-07-14
          • 2021-07-07
          • 2018-05-07
          • 2017-10-27
          • 1970-01-01
          • 1970-01-01
          • 2017-06-16
          • 2018-06-22
          相关资源
          最近更新 更多