[英]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.