简体   繁体   English

如何从 App.vue 访问组件属性

[英]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; 
  }
}

Accessing child component's data in parent component in vuejs在 vuejs 的父组件中访问子组件的数据

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 的子组件,您可以使用propsevents相互通信。

  1. props : Facilitates communication from parent to child. props :促进父母与孩子之间的交流。
  2. 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>

Custom component with v-model带有 v-model 的自定义组件

This needs two requirements .这需要两个要求

  1. You have a prop on the child component with the name value .您在子组件上有一个名为value的道具。

     props: ['value'], // this part in the child component snippet
  2. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM