[英]How to access a component property from App.vue
我使用 vue-loader 来帮助我安装 vue 和 webpack 我有一个名为 App.vue 的文件
在 App.vue 中,我添加了一个名为 widget 的组件。 如果我单击了某个按钮,则会有一个设置btnClicked = true
的函数,因此会出现小部件
<widget v-show="btnClicked"></widget>
但我也希望该函数能够访问widgetShowMe
,它是我组件中的一个属性。
我希望在我的App.vue
中激活的功能也设置widgetShowMe = true
我试过了,但没有用
methods:{
btnClickedFunc () {
this.btnClicked = true;
Widget.widgetShowMe = true;
}
}
如果您有一个称为parent
的父组件和一个称为 child 的子组件,您可以使用props
和events
相互通信。
props
:促进父母与孩子之间的交流。events
:可用于将子组件中的数据传递给父组件。 对于这个问题,我们需要事件并将使用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>
这需要两个要求。
您在子组件上有一个名为value
的道具。
props: ['value'], // this part in the child component snippet
您使用该值发出事件input
。
this.$emit('input', this.result) // this part in the child component snippet
您需要考虑的是,何时使用widgetShowMe
的值发出事件,并且您的app.vue
可以轻松捕获widget
中的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.