[英]How to access a component property from App.vue
I used vue-loader to help me install vue and webpack I have a file called App.vue我使用 vue-loader 来帮助我安装 vue 和 webpack 我有一个名为 App.vue 的文件
In App.vue I added a component called widget.在 App.vue 中,我添加了一个名为 widget 的组件。 If I clicked some button there's a function that set the
btnClicked = true
hence the widget appears如果我单击了某个按钮,则会有一个设置
btnClicked = true
的函数,因此会出现小部件
<widget v-show="btnClicked"></widget>
but I also want that function to access the widgetShowMe
, it's a property in my component.但我也希望该函数能够访问
widgetShowMe
,它是我组件中的一个属性。
I want the function activated in my App.vue
to also set widgetShowMe = true
I tried this but it didn't work我希望在我的
App.vue
中激活的功能也设置widgetShowMe = true
我试过了,但没有用
methods:{
btnClickedFunc () {
this.btnClicked = true;
Widget.widgetShowMe = true;
}
}
If you have a parent component called parent
and child component called child, you can communicate between each other using props
and events
.如果您有一个称为
parent
的父组件和一个称为 child 的子组件,您可以使用props
和events
相互通信。
props
: Facilitates communication from parent to child. props
:促进父母与孩子之间的交流。events
: Can be used to pass data in a child component to the parent component. events
:可用于将子组件中的数据传递给父组件。 For this question we require events and will use v-model
to make the child component usable everywhere with much less setup.对于这个问题,我们需要事件并将使用
v-model
使子组件在任何地方都可以使用,并且设置更少。
Vue.component('counter', { template: `<div><button @click='add'>+1</button> <button @click='sub'>-1</button> <div>this is inside the child component: {{ result }}</div></div>`, data () { return { result: 0 } }, props: ['value'], methods: { emitResult () { this.$emit('input', this.result) }, add () { this.result += 1 this.emitResult() }, sub () { this.result -= 1 this.emitResult() } } }) new Vue({ el: '#demo', data () { return { resultFromChild: null } } })
<script src="https://vuejs.org/js/vue.min.js"></script> <div id='demo'> <counter v-model='resultFromChild'></counter> This is in parent component {{ resultFromChild }} </div>
This needs two requirements .这需要两个要求。
You have a prop on the child component with the name value
.您在子组件上有一个名为
value
的道具。
props: ['value'], // this part in the child component snippet
You emit the event input
with the value.您使用该值发出事件
input
。
this.$emit('input', this.result) // this part in the child component snippet
All you need to think of is, when to emit the event with the value of widgetShowMe
, and your app.vue
can easily capture the value inside your widget
.您需要考虑的是,何时使用
widgetShowMe
的值发出事件,并且您的app.vue
可以轻松捕获widget
中的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.