简体   繁体   English

访问组件并从App.vue组件触发click事件

[英]Access a component and trigger click event from App.vue component

In my template I have one click event 在我的模板中,我有一个单击事件

<span v-on:click="showGalery()">

And I am using one method for it 我正在使用一种方法

export default {
  name: 'osaka',
  data: function () {
    return {
      galery: false,
    }
  },
  methods: {
    showGalery () {
      this.galery = true
    }
  }
}

Is it possible to trigger this method from App.vue template where is my nav and router links is located? 是否可以从导航和路由器链接所在的App.vue模板触发此方法?

I am using vue-webpack template. 我正在使用vue-webpack模板。 I have components, router.js, App.js and main.js structure. 我有组件,router.js,App.js和main.js结构。

Remember Vue has a one way data flow, so if you want to set something on the component you can simply pass a prop and use a watcher to trigger the change: 请记住,Vue具有单向数据流,因此,如果您想在组件上进行设置,则只需传递一个prop并使用watcher来触发更改:

Vue.component('gallery', {
  template: `<div v-show="gallery">Gallery</div>`,
  props: {
    show: {
      type: Boolean,
      default: false
    }
  },
  created() {
    this.gallery = this.show;
  },
  watch: {
    show(val) {
      this.gallery = val;
    }
  },
  data() {
    return {
      gallery: false
    }
  }
});

Then in the parent you would have: 然后在父母中,您将拥有:

new Vue({
  el: '#app',
  data: {
    showGallery: false
  }
});

And use the following markup: 并使用以下标记:

<gallery :show="showGallery"></gallery>

See this JSFiddle: https://jsfiddle.net/yx1uq370/ 看到这个JSFiddle: https ://jsfiddle.net/yx1uq370/

Incidentally, if you just want to show hide the entire component, then you can just use v-show on the component itself which 顺便说一句,如果您只想显示隐藏整个组件,则可以在组件本身上使用v-show

Vue.component('gallery', {
  template: `<div>Gallery</div>`
});

new Vue({
  el: '#app',
  data: {
    showGallery: false
  }
});

Then your markup: 然后,您的标记:

<gallery v-show="showGallery"></gallery>

And here's the fiddle for that: https://jsfiddle.net/gfr9kmub/ 这是为此的小提琴: https : //jsfiddle.net/gfr9kmub/

One final thing, are you sure that you really need to trigger this from your nav? 最后一件事,您确定确实需要从导航中触发此操作吗? I would assume that your nav would display the views and the views themselves would take care of this type of state management. 我假设您的导航将显示视图,并且视图本身将负责这种类型的状态管理。 Otherwise you may want to look at vuex to handle this situation 否则,您可能需要查看vuex来处理这种情况

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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