【问题标题】:[Vue warn]: Property or method "hp" is not defined on the instance but referenced during render[Vue 警告]:属性或方法“hp”未在实例上定义,但在渲染期间引用
【发布时间】:2020-06-22 21:06:11
【问题描述】:

我有以下代码:

var example1;
var hp = ["p"];

document.addEventListener("DOMContentLoaded", function(event) {
  hp = ["x"];
  example1 = new Vue({
    el: '#example-1', //yes i have an element with #example-1 (not relevant here)
    data: {
      iLoveMyself: window.hp
    },

    watch: {
      iLoveMyself: {
        deep: true,
        immediate: true,
        handler (val, oldVal) {
          console.log("yeeeh")
        }
      }
    }
  })
});

我尝试了很多东西(这就是为什么我的代码 ^ 如此丑陋)但我保留了这个 console.error:

vue.js:634 [Vue warn]: Property or method "hp" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

如果我在 VueJs 的 chrome 插件中查找值,数据集如下:

iLoveMyself:Array[1]
0:"x"

到目前为止一切都很好,但是当尝试更新 hp 时:

hp.push("y");
hp.pop();
hp = "ZEBRA";

我没有得到任何回应。

什么是我不明白的?

提前表示感谢!

编辑: 所以毕竟我开始收集碎片,我的html毕竟很重要:/

<div id="example-1">
  <div v-for="ev in hp" :key="ev.beavus">
    {{ ev.beavus }}
  </div>
</div>

【问题讨论】:

  • 该错误表明您正在尝试在模板中使用名为hp 的属性。但是,您尚未在 Vue 实例上定义名为 hp 的属性。在示例代码中,您有一个名为iLoveMyself 的属性。您有一个名为hp 的变量,但在模板中无法访问它,即使它是全局变量。它必须是实例的属性,否则模板将无法看到它。
  • 请分享模板
  • @skirtle 我很困惑,请给我一点时间
  • @BoussadjraBrahim 我进行了编辑
  • v-for="ev in hp" 引用 hp。您需要将其更改为 iLoveMyself 以匹配实例上的属性。要么将iLoveMyself重命名为hp

标签: javascript vue.js vuejs2 vue-component


【解决方案1】:

这是您在问题中发布的更惯用的 Vue 实现:

new Vue({
  el: '#example-1',

  data: {
    iLoveMyself: [{beavus: "x"}]
  },

  watch: {
    iLoveMyself: {
      deep: true,
      immediate: true,
      handler (val, oldVal) {
        console.log("yeeeh")
      }
    }
  },
  
  methods: {
    add () {
      this.iLoveMyself.push({beavus: Math.random()})
    }
  }
});
<script src="https://unpkg.com/vue@2.6.11/dist/vue.js"></script>

<div id="example-1">
  <div v-for="ev in iLoveMyself" :key="ev.beavus">
    {{ ev.beavus }}
  </div>
  <button @click="add">Add</button>
</div>
  

我已经摆脱了全局变量,现在只有一个名为 iLoveMyself 的实例属性来保存数组。将额外数据推送到数组会触发 watch 并使用新数据更新 DOM。

【讨论】:

    【解决方案2】:

    你应该这样做:

    <div id="example-1">
      <div v-for="ev in iLoveMyself" :key="ev.beavus">
        {{ ev.beavus }}
      </div>
    </div>
    
    

    【讨论】:

    • 是的,确实消除了错误,但在更新 var hp 时仍然没有响应
    • 该属性不是响应式的,请准确说明您的用例,我们希望找到一种尊重 Vue 范式的方法
    • 我认为使用可观察到的适合您的情况请查看这篇文章vuedose.tips/tips/creating-a-store-without-vuex-in-vue-js-2-6
    猜你喜欢
    • 2019-02-20
    • 2021-11-27
    • 2019-08-12
    • 2018-09-24
    • 2017-11-14
    • 2020-04-01
    • 2021-08-13
    相关资源
    最近更新 更多