Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.5k views
in Technique[技术] by (71.8m points)

vue.js - How to access App.vue from another component?

in my app written with VueJs 2, I have into the Vue.app this code:

export default {
  name: 'app',
  data () {
    return {
      title: 'Gestione fornitori',
      idfornitore: ''
    }
  },

  methods: {
    loadFunction (route) {
      this.$router.push(route)
    }
  }
}
</script>

I wish to access the property idfornitore from another component, I've used:

    mounted () {
      this.$parent.idfornitore = ''
    },

or also:

    mounted () {
      var Vue = require('vue')
      Vue.app.idfornitore = ''
    },

But it didn't worked. Which is the correct way to access the property from another component?

Thank you in advance.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
  • Use props to communicate data from parent to child.

  • Emit events to communicate from child to parent

Parent.vue

    <template>
      <div>
         <h2>Parent: {{idfornitore}}</h2>
         <child :idfornitore="idfornitore" @changevalue="idfornitore = $event"></child>
         //idfornitore - data sent to child from parent.
         //changevalue - event emitted from child and received by parent
      </div>
    </template>

    <script>
    import Child from './compname.vue';

    export default {
        components:{
            "child" : Child
        },
        data(){
            return {
                idfornitore : "34"
            }
        }
    }
    </script>

Child.vue

<template>
  <div>
    Child: {{idfornitore}}
    <button @click="add()">Add</button>
  </div>
</template>
<script>
export default {
       props:["idfornitore"],
       methods : {
           add(){
               this.idfornitore++; // mutating props directly will result in vuejs warning. i have used this code here to show how this works.
               this.$emit("changevalue",this.idfornitore); //cascade the update to parent
           }
       }
    }
</script>
  • if you feel communicating through props results in tight coupling, then the more convenient approach would be using eventBus

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...