【问题标题】:Vue - Instantiate component in custom directiveVue - 在自定义指令中实例化组件
【发布时间】:2020-05-25 18:11:05
【问题描述】:

我想通过显示一个弹出框来保护一些需要身份验证的操作,以便向未经身份验证的用户登录/注册。

我想要这样的东西:

<button require-auth>Like</button>

当您在未经身份验证的情况下单击它时,会出现一个弹出框(我使用的是 Bootstrap Vue 弹出框),告诉您登录以继续。

为此,我创建了一个自定义指令,用于监听点击事件并检查用户的身份验证状态。问题是我不知道如何从那里实例化 popover 组件并显示它。

实际上这是我尝试过但没有成功的方法:

export const Authenticated: DirectiveOptions = {
  bind (el, binding, vnode) {
    el.addEventListener('click', (event) => {
      if (store.getters['users/authenticated']) {
        return;
      }

      event.preventDefault();

      const node = document.createElement('div');

      const placement = get(binding, 'value', 'auto');
      const template = `
        <p>Vous devez être connecté pour effectuer cette action</p>
        <div>
          <b-button block :to="{ name: 'login' }">Se connecter</b-button>
          <b-button block :to="{ name: 'register' }">S'inscrire</b-button>
        </div>`;

      const popover = new BPopover({
        propsData: { target: el, placement },
      });

      popover.$slots.default = [template as any];
      popover.$slots.title = ['Connexion requise' as any];

      popover.$mount(node);
      popover.$emit('open');

      console.log(popover.$el) // which log : <---->
    })
  },
};

我知道我可以使用组件来执行此操作,但我希望它可以与任何类型的按钮一起使用,因此我必须使用插槽并包裹在​​ div 中,这会破坏页面的结构.

如何正确触发弹窗?

【问题讨论】:

    标签: javascript vue.js vuejs2 vue-component vue-directives


    【解决方案1】:

    在弹出窗口中:v-if="notAuthenticated"

    按钮上:@click="checkAuth"

    在钩子里:

    data() {
        return {
            notAuthenticated: false
        }
    },
    methods: {
        checkAuth () {
            if (this.isAuthenticated)
                //do whatever
            } else {
                this.notAuthenticated= true;
            }
        }
    }
    

    并在弹出窗口关闭、单击按钮等时将notAuthenticated 改回来。

    【讨论】:

    • 我可以为每个按钮管理弹出框,但是页面可以有很多这样的操作,所以我想创建一个可重用的指令,自动检查弹出框并将其绑定到元素,而不是重新定义每个组件中popover的功能和模板
    猜你喜欢
    • 2019-01-29
    • 2020-07-19
    • 2018-10-20
    • 1970-01-01
    • 2019-11-06
    • 2020-08-26
    • 1970-01-01
    • 2017-08-22
    • 2019-03-07
    相关资源
    最近更新 更多