如何从另一个vue文件中获取数据?

发布于 2025-02-08 01:04:59 字数 594 浏览 1 评论 0原文

如下所示,A.Vue文件具有元素数据返回一些数字值

<template></template>
<script>
  export default {
     data(){
       return{
         element: [
           {
             number:'11'
           }
           {
             number:'22'
           } 
         ]
       }
     }
  }
</script>

,现在我想从 a.vue b.vue 。有办法做到吗?我看到了单击按钮的解决方案,但我不想使用按钮传递数据。

b.vue文件

<template>
  <div>I want to get element.length here</div>
</template>

As the code show below, A.vue file has element data return some number values

<template></template>
<script>
  export default {
     data(){
       return{
         element: [
           {
             number:'11'
           }
           {
             number:'22'
           } 
         ]
       }
     }
  }
</script>

Now I want to get element.length from A.vue to B.vue. Is there a way to do that? I saw a solution with button click but i dont want to use button to pass data.

B.vue file

<template>
  <div>I want to get element.length here</div>
</template>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

南城追梦 2025-02-15 01:05:00

您可以通过将prop(包含元素数组的长度)从a.vue组件传递到b.vue组件来实现它。这是现场演示

Vue.component('bcomponent', {
  // declare the props
  props: ['length'],
  // just like data, the prop can be used inside templates
  // and is also made available in the vm as this.message
  template: '<div>Element length: {{ length }}</div>',
});

var app = new Vue({
  el: '#app',
  data: {
    element: [{
      number: '11'
    }, {
      number: '22'
    }]
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<!-- Component A -->
<div id="app">
  <BComponent :length="element.length">
  </BComponent>
</div>

You can simply achieve it by passing prop (which contains the length of the element array) from A.vue component to B.vue component. Here is the live demo :

Vue.component('bcomponent', {
  // declare the props
  props: ['length'],
  // just like data, the prop can be used inside templates
  // and is also made available in the vm as this.message
  template: '<div>Element length: {{ length }}</div>',
});

var app = new Vue({
  el: '#app',
  data: {
    element: [{
      number: '11'
    }, {
      number: '22'
    }]
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<!-- Component A -->
<div id="app">
  <BComponent :length="element.length">
  </BComponent>
</div>

黑寡妇 2025-02-15 01:05:00

如果可能的话,只需将数据作为Prop从B传递到A,这样您就可以在数据上实现任何逻辑。
如果不是这样,则应将VUEX使用用于数据存储,因此任何组件都可以访问它。

If it's possible, just pass the data as a prop from B to A, this way you can implement any logic on the data.
If it's not, you should use vuex for data storage, so any component can access it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文