【问题标题】:How to pass global variable from parent to child in Vuejs?如何在Vuejs中将全局变量从父级传递给子级?
【发布时间】:2017-08-11 23:52:34
【问题描述】:

我有一个名为 Profile.vue 的页面,其结构如下,

<style>
</style>
<template>
 <component-1></component-1>
 <component-2></component-3>
 <component-3></component-3>
 </template>
<script>
 import component1 from '...../..'
 import component2 from '...../..'
 import component3 from '...../..'
 export default {
 name: 'profile',
 data(){
    return{
        pagename: 'Profile',
        mydata: 'This is my data'
    }
  }
}
</script>

如何使 mydata 中的数据对我正在导入的所有组件可用,即如何传递对所有组件可用的数据?

【问题讨论】:

  • 所以你想将mydata 传递给所有子组件?
  • @lamelemon 是的。我想给所有子组件添加数据

标签: javascript vue.js global-variables vuejs2 mixins


【解决方案1】:

您可以使用props

<component-1 v-bind:message="mydata"></component-1>

然后在您的子组件中(直接来自文档):

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

【讨论】:

    【解决方案2】:

    您可以使用 $parent(或 $root)访问变量,而不是使用 props(这可能意味着您必须经常传递这些 props)

    Vue.component('component-1', {
      computed: {
        message: function(){
          // this is how to access the variable inside the component code
          return this.$parent.message;
        },
      },
      // and because of using computed, access it inside the template
      template: '<span>{{ message }}</span>'
    })
    

    【讨论】:

      【解决方案3】:

      您只是导入了一些未继承的组件,因此您无法共享这样的数据。 将组件添加到父组件的组件字段中,如下所示: https://vuejs.org/v2/guide/components.html#Local-Registration 然后在子组件中你可以使用 this.$parent。而 this.$parent.mydata 在你的例子中

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-11-14
        • 1970-01-01
        • 1970-01-01
        • 2017-12-24
        • 2017-12-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多