簡體   English   中英

如何從 App.vue 訪問組件屬性

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

在 vuejs 的父組件中訪問子組件的數據

如果您有一個稱為parent的父組件和一個稱為 child 的子組件,您可以使用propsevents相互通信。

  1. props :促進父母與孩子之間的交流。
  2. 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>

帶有 v-model 的自定義組件

這需要兩個要求

  1. 您在子組件上有一個名為value的道具。

     props: ['value'], // this part in the child component snippet
  2. 您使用該值發出事件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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM