【问题标题】:Vue - Call beforeMount method from vue fileVue - 从 vue 文件调用 beforeMount 方法
【发布时间】:2020-09-28 13:19:05
【问题描述】:
I am trying to call `beforemount()` method from "A" file  , this file is imported in another file which is called on homepage that is "B".

I am not sure what i am missing here.

问题是“A”文件中的beforemount() 方法没有调用,而是文件 “B”具有调用前端的相同方法,似乎组件没有在父文件中被调用(我在父文件中安装之前也有(文件B也是) 这是我在两个文件中添加的潜在代码,请查看并告诉我

         File B

            <script>

            import A from 'one/components/theme/A.vue'

            export default {
              data () {
                return {
                  A
                },
    components: {
        A
      }
              }

            </script>


            FILE A

            <template>
              <div class="A"/>
            </template>

            <script>

            export default {
              name: 'A',
              beforeMount () {
                console.log('segment beforeMount')

              },
            }

【问题讨论】:

  • 至少您缺少问题中的代码;)
  • 请再次检查问题,更新问题

标签: vue.js vuejs2 vue-component vuex


【解决方案1】:

让我们用其他的命名约定来解释这个,我们有ParentComponent.vue和ChildComponent.vue,想法是在ParentComponent.vue组件中使用ChildComponent.vue:

// ChildComponent.vue
<template>
  <div>
    <p>I'm the child component</p>
  </div>
</template>
<script>
  export default {
    name: "ChildComponent",
    beforeMount () {
     console.log('segment beforeMount in child')
    },
  }
</script>

现在让我们看看父组件:

// ParentComponent.vue
<template>
  <div>
    <p>I'm the {{ message }} component</p>
    <ChildComponent />
  </div>
</template>
import ChildComponent from './routeToChildComponent/ChildComponent.vue'
<script>
  export default {
    name: "ParentComponent",
    // register the components to use
    components: {
      ChildComponent
    },
    data: () => ({
      message: "Parent"
    }),
    beforeMount () {
     console.log('segment beforeMount in parent')
    },
  }
</script>

这样,ParentComponent 就可以访问子组件,并且都运行 beforeMount Hook。

【讨论】:

  • 我也有 beforeMount 在父文件中,当前执行,使用你的代码后,beforeMount() 应该执行两次,这就是我想要的
  • 再检查一遍。
  • 在您的代码中,您在 B 的数据属性中返回 A,为什么?
  • 我有一些要求,感谢代码和正确的语法,正确的代码。
【解决方案2】:

你必须在 B 的 compoennts 范围内声明导入的组件 A,然后在 B 的模板中实际使用该组件 A。

文件B

<template>
  <div>
    <A />
  </div>
</template>
<script>
import A from 'one/components/theme/A.vue';
export default {
  components: { A }
}
</script>

文件 A 保持不变

【讨论】:

  • 先生,我已经这样做了,但是在文件“A”中的挂载方法没有执行之前
  • 组件Segment 来自哪里?你没有导入它。你不想打电话给FILE A的beforeMount吗?然后作为答案状态,您必须在 B 的组件范围内声明 A。并在 B 的模板中调用 A。
  • beforeMount 也在“B”和“A”中的两个文件中,“B”也是父级,parenr 中的 beforeMount 被执行,但是,它没有在子文件“A”中执行跨度>
  • 你必须从 B 的模板中调用 A 在 B 的模板中``` 另外请从data() B 中的函数。
  • 从 B 中的 data() 函数中移除了 A,
猜你喜欢
  • 2018-07-16
  • 1970-01-01
  • 2021-04-09
  • 2018-05-30
  • 1970-01-01
  • 2018-05-27
  • 2020-08-19
  • 2019-05-28
  • 1970-01-01
相关资源
最近更新 更多