Vue Ошибка CLI: свойство или метод "data" не определены в экземпляре - PullRequest
1 голос
/ 02 апреля 2020

Я столкнулся с проблемой в моем Vue проекте при попытке визуализации данных из локального JSON. Я прочитал инструкции и следовал им - каждый шаг - но ошибка преобладает. Поскольку я новичок в Vue и в самом продвинутом программировании, я обращаюсь за помощью.

engli sh. json

{
  "0": {
    "text": "This be a square",
    "color": "blue",
    "size": "small"
  },
  "1": {
    "text": "here lies a square",
    "color": "red",
    "size": "medium"
  },
  "2": {
    "text": "Tharr be a squaree",
    "color": "black",
    "size": "large"
  }
}

ExperienceText . vue

<template>
  <article class="content__box" :v-for="data in expJson">
    {{data.text}}
    <h6>{{data.text}}</h6>
    <h3>{{data.color}}</h3>
    <p>{{data.size}}</p>
  </article>
</template>
<script>
import json from "@/components/json/english.json";
export default {
  name: "ExperienceText",
  data() {
    return {
      expJson: json
    };
  }
};
</script>

Ошибка

[Vue warn]: свойство или метод "data" не определены в экземпляре, но на них ссылаются во время рендеринга. Убедитесь, что это свойство является реактивным, либо в параметре данных, либо для компонентов на основе классов, инициализируя свойство. См .: https://vuejs.org/v2/guide/reactivity.html#Declaring -Reactive-Properties .

found in

---> <ExperienceText> at src/components/mainComp/subComp/ExperienceText.vue
       <ExperienceSection> at src/components/mainComp/ExperienceSection.vue
         <Experience> at src/components/mainComp/Experience.vue
           <Main> at src/components/Main.vue
             <Container> at src/views/Container.vue
               <App> at src/App.vue
                 <Root>

Show 60 more frames
vue.runtime.esm.js?2b0e:619 [Vue warn]: Property or method "data" 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.

found in

---> <ExperienceText> at src/components/mainComp/subComp/ExperienceText.vue
       <ExperienceSection> at src/components/mainComp/ExperienceSection.vue
         <Experience> at src/components/mainComp/Experience.vue
           <Main> at src/components/Main.vue
             <Container> at src/views/Container.vue
               <App> at src/App.vue
                 <Root>

vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in render: "TypeError: Cannot read property 'text' of undefined"

found in

---> <ExperienceText> at src/components/mainComp/subComp/ExperienceText.vue
       <ExperienceSection> at src/components/mainComp/ExperienceSection.vue
         <Experience> at src/components/mainComp/Experience.vue
           <Main> at src/components/Main.vue
             <Container> at src/views/Container.vue
               <App> at src/App.vue
                 <Root>

vue.runtime.esm.js?2b0e:1888 TypeError: Cannot read property 'text' of undefined
    at Proxy.render (eval at ./node_modules/cache-loader/dist/cjs.js?{"cacheDirectory":"node_modules/.cache/vue-loader","cacheIdentifier":"db619a62-vue-loader-template"}!./node_modules/vue-loader/lib/loaders/templateLoader.js?!./node_modules/cache-loader/dist/cjs.js?!./node_modules/vue-loader/lib/index.js?!./src/components/mainComp/subComp/ExperienceText.vue?vue&type=template&id=088f3b1e& (app.js:1089), <anonymous>:15:36)
    at VueComponent.Vue._render (vue.runtime.esm.js?2b0e:3548)
    at VueComponent.updateComponent (vue.runtime.esm.js?2b0e:4066)
    at Watcher.get (vue.runtime.esm.js?2b0e:4479)
    at new Watcher (vue.runtime.esm.js?2b0e:4468)
    at mountComponent (vue.runtime.esm.js?2b0e:4073)
    at VueComponent.Vue.$mount (vue.runtime.esm.js?2b0e:8415)
    at init (vue.runtime.esm.js?2b0e:3118)
    at createComponent (vue.runtime.esm.js?2b0e:5978)
    at createElm (vue.runtime.esm.js?2b0e:5925)

JSON прибыло

Proof of json data reached.

В моем приложении тег статьи вообще не виден. Я почти уверен, что это потому, что данные JSON не отображаются должным образом. Как мне исправить эту проблему?

Ответы [ 2 ]

2 голосов
/ 02 апреля 2020

Во-первых, удалите : из v-for, поскольку это директива, а не привязка.

<article class="content__box" v-for="data in expJson">

Вы также хотите :key для всех v-for элементов. Поскольку ваши данные не имеют уникального идентификатора, мы можем использовать индекс:

<article class="content__box" v-for="(data, index) in expJson" :key="index">

Кроме того, это все равно дает ошибку, поскольку все компоненты должны иметь один root элемент и v-for может создать потенциально несколько root элементов. Вы можете обернуть все в div:

<template>
  <div>
    <article class="content__box" v-for="(data, index) in expJson" :key="index">
      {{data.text}}
      <h6>{{data.text}}</h6>
      <h3>{{data.color}}</h3>
      <p>{{data.size}}</p>
    </article>
  </div>
</template>
0 голосов
/ 02 апреля 2020

Надеюсь, это поможет.

удалить : двоеточие из :v-for

const yourJson = {
  "0": {
    "text": "This be a square",
    "color": "blue",
    "size": "small"
  },
  "1": {
    "text": "here lies a square",
    "color": "red",
    "size": "medium"
  },
  "2": {
    "text": "Tharr be a squaree",
    "color": "black",
    "size": "large"
  }
}

new Vue({
  el: '#app',
  data() {
    return {
      expJson: yourJson,
    };
  },
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <article class="content__box" v-for="data in expJson" :style="{backgroundColor: data.color}" style="color: white; padding: 10px">
    {{data.text}}
    <h6>{{data.text}}</h6>
    <h3>{{data.color}}</h3>
    <p>{{data.size}}</p>
  </article>
</div>
...