Kentico内容和Vue 3

qjp7pelc  于 2022-11-17  发布在  Vue.js
关注(0)|答案(1)|浏览(108)

我正在寻找一个简单的例子,说明如何使用Kontent的数据在Vue 3中创建一个组件。更具体地说,我正在尝试列出某种内容类型的项目。我试图重构Kentico提供的Vue示例应用程序,但我对编程和Vue相当陌生,似乎无法理解...
下面的代码给出错误消息Cannot read property 'name' of undefined

<template v-for="(item, index) in eventsData" :key="index">
  <p>{{ item.name }}</p>
</template>

<script>
import { Client } from "../Client"; //seperated this, the connection works

export default {
  name: 'Test',
  setup() {
    const data = Client
    .items()
    .type("event")
    .toObservable()
    .subscribe(response => {
      console.log(response) //this works, data is displayed in the console
      return response.items;
    });

    return {data};
  },
  computed: { 
    eventsData: function() {
      return this.data.map(event => ({
        name: event.name
      }));
    }
  },
}
</script>

Edit2:根据eyeslandic的提示,我试图改进我的代码,但是我又卡住了。setup()内部的变量在它外部是不可访问的,那么我如何得到data()的结果呢?
这就是我现在所拥有的:

<template>
  <div class="test-div">
    <template v-for="(item, index) in eventsData" :key="index">
      <p>{{item.name}}</p>
    </template>
  </div>
</template>

<script>
import { Client } from "../Client";

export default {
  name: 'Test',
  setup() {
    let events = [];

    const kontent = Client
    .items()
    .type("event")
    .toObservable()
    .subscribe(response => {
      console.log(response);//this works
      events = response.items;
      console.log("events inside kontent variable: " + events)//[object object][object object]
    });

    console.log("events outside kontent variable: " + events);//nothing
    console.log("kontent inside setup: " + kontent)//[object object]

    return {
      events,
      kontent
    };
  },  
  data() {
    return {
      eventList: events, //error: undefined,
      eventList2: kontent //error: undefined
    }
  },
  computed: {
    eventsData: function() {
      return this.eventList.map(event => ({
        name: event.name.value
      }));
    }
  }
}
</script>
piztneat

piztneat1#

events必须是refreactive才能React。此外,您可以使用Composition API的computedsetup()创建计算属性:

<template>
  <p v-for="(name, index) in eventList" :key="index">
    {{ name }}
  </p>
</template>

<script>
import { computed, reactive } from 'vue'

export default {
  setup() {
    const events = ref([])
  
    Client.items()
      .type('event')
      .toObservable()
      .subscribe(response => events.value = response.items)

    return {
      eventList: computed(() => events.value.map(event => ({ name: event.name.value }))
    }
  }
}
</script>

没有必要从setup()返回eventskontent,因为它们在模板中的任何地方都没有使用。我看到您试图在data()中引用kontent,但是eventListeventList2也没有使用。您显示的模板可以完全依赖于setup(),并使用上面显示的解决方案。

相关问题