如何从另一个组件访问App.vue?

Rob*_*llo 2 components vue.js vue-component vuejs2

在用VueJs 2编写的应用程序中,我将以下代码插入Vue.app:

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

  methods: {
    loadFunction (route) {
      this.$router.push(route)
    }
  }
}
</script>
Run Code Online (Sandbox Code Playgroud)

我希望idfornitore从另一个使用过的组件访问该属性:

    mounted () {
      this.$parent.idfornitore = ''
    },
Run Code Online (Sandbox Code Playgroud)

或者:

    mounted () {
      var Vue = require('vue')
      Vue.app.idfornitore = ''
    },
Run Code Online (Sandbox Code Playgroud)

但这没有用。从另一个组件访问属性的正确方法是哪种?

先感谢您。

div*_*ine 6

  • 使用道具将数据从父母传递给孩子。

  • 发出事件以使孩子与父母沟通

亲子

    <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>
Run Code Online (Sandbox Code Playgroud)

小孩

<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>
Run Code Online (Sandbox Code Playgroud)
  • 如果您觉得通过道具进行交流会导致紧密耦合,那么更方便的方法是使用eventBus