Vue 3React属性无法获取阵列数据

kupeojn6  于 2023-02-19  发布在  Vue.js
关注(0)|答案(1)|浏览(95)

我不能使用我的被动组件的数组,因为它在一个代理中。我尝试用json.stringfy获取代理中的值,但只得到一个空数组。我该如何使用我的数组?

//index.js
app.config.globalProperties.$s = reactive({ component: undefined });

export default {
    name: 'component',
    data() {
        return {
            array: [],
        }
    },

    created() {
        this.$s.component = this;
        this.array = [{name: 'test'}];
    },

//   template in child component
    <ul>
      <li v-for="a in $s.parent.array"  <- this is not working becouse my array is in a proxy
      </li>
    </ul>

}

console.log(this.array) -> Proxy { <target>: (1) […], <handler>: {…} }
vq8itlhq

vq8itlhq1#

您可以使用Composition API进行全局数据存储,另一种选择是使用Pinia
Playground

const { createApp, reactive } = Vue;

const mydata = reactive({ array: [] });

const MyComponent = {
  props: {
      array: {      
        type: Array,
        default: []
      }
  },
  template: `
  My Component: 
  <ul>
      <li v-for="a in array">{{a}}</li>
  </ul>`
}

const App = {
  components: { MyComponent },
  setup() {    
    return { mydata }
  },
  created() {
     this.mydata.array = ['test'];
  }
}
const app = createApp(App);
app.mount('#app');
#app { line-height: 1.5; }
[v-cloak] { display: none; }
<div id="app" v-cloak>
  mydata.array: {{mydata.array}}<br/>
 <my-component :array="mydata.array"></my-component> 
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>

相关问题