【问题标题】:How to call a method on vue component after it rendered in storybook?在故事书中渲染后如何调用vue组件上的方法?
【发布时间】:2020-07-17 17:13:40
【问题描述】:

我的问题是组件在故事书中呈现后调用方法。它是关于显示一个模态的,但它可以应用于任何 vue 组件。
我需要在这里调用方法showDialog(true)创建组件后使其可见。

【问题讨论】:

    标签: vue.js storybook


    【解决方案1】:

    这是使用带有 component story format of storybook (version 5.2+) 的 Typescript 的棘手解决方案:

    import Vue from 'vue';
    
    // ... some imports and global setup 
    
    export const normalError = () => ({
      components: { 'error-modal': ErrorModal },
      template: `<error-modal @hook:mounted='externalMount'/>`, // bind the custom method on mounted hook
      methods: {                           // bind the new method to the component
        async externalMount() {            // don't use an arrow function or this will have wrong scope
          const anyThis: any = this;
          const vm = anyThis.$children[0]; // target the component ErrorModal
          await Vue.nextTick();            // wait that mounted() finished
          vm.showDialog(true);             // finally show the modal / call the method !
        }
      }
    });
    

    如果你找到更好的,我会很高兴知道并支持它。

    【讨论】:

      【解决方案2】:

      这是我们项目中使用故事书 6.1 的示例。它在组件已安装

      时执行代码
      <Preview>
        <Story name="The equipment">
        {
          {
            components: { EquipmentView },
            template: `<EquipmentView />`,
            mounted () {
              this.$store.commit('equipmentStore/setSelectedEquipment', {
                equipmentId: 'CONT100A',
                equipmentName: 'Container 100L A',
              });
            }
          }
        }
        </Story>
      </Preview>
      

      对于这个 Vue(x) 组件

      export default class EquipmentView extends Vue {
          private storeModule = getModule(EquipmentStore);
          ...
      }
      

      我希望故事书中更多地支持打字稿(也许有人可以为此添加答案)。

      【讨论】:

        猜你喜欢
        • 2022-08-12
        • 2017-11-23
        • 2018-06-21
        • 2017-03-26
        • 2021-05-23
        • 2017-03-29
        • 1970-01-01
        • 2017-02-07
        • 1970-01-01
        相关资源
        最近更新 更多