Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
609 views
in Technique[技术] by (71.8m points)

vuejs2 - When to use the lifecycle method beforeMount in vue.js?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...