如何从另一个组件访问 App.vue? [英] How to access App.vue from another component?
问题描述
在我用 VueJs 2 编写的应用程序中,我在 Vue.app 中输入了以下代码:
出口默认{名称:'应用',数据 () {返回 {title: 'Gestione fornitori',idfornitore: ''}},方法: {loadFunction(路由){this.$router.push(路由)}}}
我希望从另一个组件访问属性 idfornitore
,我使用过:
挂载 () {this.$parent.idfornitore = ''},
或者:
挂载 () {var Vue = require('vue')Vue.app.idfornitore = ''},
但是没有用.从另一个组件访问属性的正确方法是什么?
提前致谢.
使用 props 将数据从父级传递给子级.
发出事件以从子级到父级进行通信
Parent.vue
<模板><div><h2>父级:{{idfornitore}}</h2><child :idfornitore="idfornitore" @changevalue="idfornitore = $event"></child>//idfornitore - 从父级发送给子级的数据.//changevalue - 从子级发出并由父级接收的事件
模板><脚本>从'./compname.vue'导入子项;导出默认{组件:{孩子":孩子},数据(){返回 {idfornitore : "34"}}}
Child.vue
<div>孩子:{{idfornitore}}<button @click="add()">添加</button>
模板><脚本>导出默认{道具:[idfornitore"],方法 : {添加(){this.idfornitore++;//直接修改 props 会导致 vuejs 警告.我在这里使用了这段代码来展示它是如何工作的.this.$emit("changevalue",this.idfornitore);//级联更新到父级}}}
- 如果您觉得通过 props 进行通信会导致紧耦合,那么更方便的方法是使用 eventBus
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.
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
这篇关于如何从另一个组件访问 App.vue?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!