何时使用 vue.js 中的 beforeMount 生命周期方法? [英] When to use the lifecycle method beforeMount in vue.js?

查看:83
本文介绍了何时使用 vue.js 中的 beforeMount 生命周期方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试想出一个何时使用每个 Vue.js 生命周期钩子的示例.对于 beforeMount() 我想不出任何用例.在研究时,我还阅读了:

I try to come up with an example when to use each Vue.js lifecycle hook. For beforeMount() I can't come up with any use case. While researching I have als read:

很可能我们永远不需要使用这个钩子.

Most likely we’ll never need to use this hook.

有人可以提供一个我想使用这个生命周期钩子的例子吗?

Can someone provide an example when I would like to use this lifecycle hook?

推荐答案

我能想到的最佳用例来自 使用 Symfony/Twig 直接向 Vue 应用程序注入数据.在挂载发生之前,您仍然可以在被 Vue 替换之前看到实际的、未转换的 Element.您可以访问的一个特定部分是数据属性.在下面的示例中,如果我们在到达 mounted 之前不从中取出东西,我们将丢失 data-fizz.

Best use case that I can come up with comes from Directly injecting data to Vue apps with Symfony/Twig. Before the mount happens, you can still see the actual, untransformed Element before it gets replaced by Vue. A particular piece that you can access is the data properties. In the example below, we lose data-fizz if we don't pull stuff out of it before we get to mounted.

const app = new Vue({
  el: "#app",
  data() {
    return {
      foo: "bar"
    };
  },
  template: "<div>{{foo}}</div>",
  beforeMount() {
    console.log(this.$el); // <div id="app" data-fizz="buzz"></div>
    console.log(this.$el.dataset.fizz); // buzz
  },
  mounted() {
    console.log(this.$el); // <div>bar</div>
    console.log(this.$el.dataset.fizz); // undefined
  }
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app" data-fizz="buzz"></div>

这篇关于何时使用 vue.js 中的 beforeMount 生命周期方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆