如何从 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; 
  }
}

访问child组件在vuejsparent组件中的数据

如果你有一个名为 parent 的 parent 组件和一个名为 child 的 child 组件,你可以使用 propsevents.

  1. props:促进从 parent 到 child 的通信。
  2. events:可用于将child组件中的数据传递给parent组件。

对于这个问题,我们需要事件并将使用 v-model 使 child 组件在任何地方都可用,而且设置更少。

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

的自定义组件

这需要两个requirements.

  1. 您在 child 组件上有一个名为 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中的值。