简体   繁体   English

如何在Vuejs中将全局变量从父级传递给子级?

[英]How to pass global variable from parent to child in Vuejs?

I have a page called Profile.vue which is structured like this,我有一个名为 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>

How do i make the data available in mydata, to all the components that I am importing,ie, how can I pass data that would be available to all the components?如何使 mydata 中的数据对我正在导入的所有组件可用,即,如何传递对所有组件可用的数据?

You can use props .你可以使用道具

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

Then in your child component (directly from the docs):然后在您的子组件中(直接来自文档):

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>'
})

Rather than using props (which might mean you have to pass around those props a lot) you can access variables using $parent (or $root)您可以使用 $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>'
})

You just importing some not inherited components, so you can't share data like that.您只是导入一些未继承的组件,因此您不能共享这样的数据。 Add components into components field in parent component like here: https://v2.vuejs.org/v2/guide/components.html#Local-Registration Then in child components you can use this.$parent.将组件添加到父组件的组件字段中,如下所示: https ://v2.vuejs.org/v2/guide/components.html#Local-Registration 然后在子组件中您可以使用 this.$parent。 And this.$parent.mydata in your example而 this.$parent.mydata 在你的例子中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM