【问题标题】:Vuejs 3 props are ProxyVuejs 3 道具是代理
【发布时间】:2021-04-09 18:29:50
【问题描述】:

我将数组作为道具传递给另一个组件,当我想在该组件中安装时读取此内容时,我得到了 Proxy {}。如何从这个道具中读取数据?您可以在示例中看到当我想控制台 log 道具时,结果是 Proxy {}。我可以在 HTML 结构中看到所有值,但在挂载的控制台中看不到。

<template>
  <div class="custom-select-container">
    <div class="selected-item" @click="openSelect">
      <span class="selected-items-text">{{ selectedItem.name }}</span>
      <span class="icon-arrow1_b selected-items-icon" :class="{ active: showOptions }" />
    </div>
    <transition name="fade">
      <ul v-show="options.length && showOptions" class="custom-select-options">
        <li v-for="(option, index) in options" :key="index" class="custom-select-item">{{ option.name }}</li>
      </ul>
    </transition>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'

export default {
  props: {
    options: {
      type: Array,
      default: () => []
    }
  },

  setup(props) { 
    let showOptions = ref(false);
    let selectedItem = ref(props.options[0])

    const openSelect = () => {
      showOptions.value = !showOptions.value
    }

    onMounted(() => {
      console.log('test', props.options)
    })

    return { 
      openSelect,
      showOptions,
      selectedItem
    }
  }
}
</script>

我传递数据的父组件:

<template>
  <div class="page-container">
    <div>
      <div class="items-title">
        <h3>List of categories</h3>
        <span>({{ allCategories.length }})</span>
      </div>
      <div class="items-container">
        <div class="item" v-for="(category, index) in allCategories" :key="index">
          <span class="item-cell size-xs">{{ index + 1 }}.</span>
          <span class="item-cell size-l">{{ category.name }}</span>
        </div>
      </div>
    </div>
    <custom-select
      :options="allCategories"
    />
  </div>
  
</template>

<script>
import CustomSelect from '../components/Input/CustomSelect'
import { computed } from 'vue'
import { useStore } from 'vuex'

export default {
  components: {
    CustomSelect
  },

  computed: {
  
  },

  setup() {
    const store = useStore()

    const allCategories = computed(() => store.getters['categories/getAllCategories'])

    return {
      allCategories
    }
  }
}
</script>

【问题讨论】:

  • @BoussadjraBrahim 我上传了代码。你可以看到我什么时候想控制台 log prop,结果是 Proxy {}
  • 你确定组件挂载时你的prop不为空吗?你从哪里得到数据options?你能证明你是怎么通过的吗?
  • 你应该可以调用 this.options
  • 是的,因为我可以看到 HTML 结构中的所有值。只有在控制台中,当我进行控制台登录时,我看不到阵列,只有代理 {}。

标签: vue.js vuejs3


【解决方案1】:

这就是reactivity 在 Vue3 中的工作方式。

使用

console.log(JSON.parse(JSON.stringify(data))

console.log(JSON.stringify(data, null, 2))

在控制台中显示代理的内容

【讨论】:

  • 好的,但为什么它是空的?
  • @kasp3rsky 那是因为它是一个空数组,当您尝试将其记录到控制台时。
猜你喜欢
  • 2021-07-07
  • 2020-09-10
  • 2021-06-06
  • 2019-03-02
  • 2018-05-10
  • 2020-03-28
  • 2017-09-14
  • 1970-01-01
  • 2021-04-18
相关资源
最近更新 更多