gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 22:30:54 25 4
gpt4 key购买 nike

在我用 VueJs 2 编写的应用程序中,我在 Vue.app 中加入了这段代码:

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

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

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

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

或者还有:

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

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

提前谢谢你。

最佳答案

  • 使用 props 在 parent 与 child 之间传递数据。

  • 发出事件以在 child 与 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>
  • 如果您觉得通过 props 进行通信会导致紧耦合,那么更方便的方法是使用 eventBus

关于vue.js - 如何从另一个组件访问 App.vue?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48319480/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com