Share 5 little knowledge about Vue, hope it will be helpful to you (3)

Hello everyone, the last two articles "Share 5 little knowledge about Vue, I hope it will be helpful to you (1)" and "Share 5 little knowledge about Vue, I hope it will be helpful to you (2)" , today We continue to share 5 little knowledge about Vue, hoping to help you.

1. Use Vue.js to scroll to an element

63bae2cbfb891bd2d9f330e0d7f710b9.png

We can scroll to an element using Vue.js by assigning a reference to the element we want to scroll to. We can then call the scrollIntoView method on the element assigned to the reference to scroll to that element. For example, we can write:

<template>
  <div id="app">
    <button @click="scrollToElement">scroll to last</button>
    <p v-for="n of 100" :key="n" :ref="n === 100 ? 'last' : undefined">
      {
    
    { n }}
    </p>
  </div>
</template>
<script>
export default {
  name: "App",
  methods: {
    scrollToElement() {
      const [el] = this.$refs.last;
      if (el) {
        el.scrollIntoView({ behavior: "smooth" });
      }
    },
  },
};
</script>

We have a button called scrollToElement that calls this method. Then we have some p elements, where the last reference is assigned to the last p element. In the scrollToElement method, we use this.$refs.last to get the element assigned to the last reference by destructuring. Then we call el.scrollIntoView and use an object with a behavior property to change the scrolling behavior.

2. How to monitor window scrolling events in Vue.js components?

We can call the window.addEventListener method to listen to the scroll event on the browser window, so as to listen to the window scroll event in the Vue.js component.

For example, we could write this:

<template>
  <div id="app">
    <p v-for="n of 100" :key="n">{
    
    { n }}</p>
  </div>
</template>
<script>
export default {
  name: "App",
  created() {
    window.addEventListener("scroll", this.handleScroll);
  },
  destroyed() {
    window.removeEventListener("scroll", this.handleScroll);
  },
  methods: {
    handleScroll(event) {
      console.log(window.scrollY);
    },
  },
};
</script>
  • We call the window.addEventListener method in the created hook and pass the 'scroll' parameter to add the handleScroll scroll event listener to listen to the scroll event when the component is mounted.

  •  In the destroyed hook, we call the window.removeEventListener method to remove the handleScroll scroll event listener.

  • In the handleScroll method, we use the window.scrollY property to get the vertical scroll position.

  • In the template we have some scrollable content. If we scroll through it, we should see the value of scrollY recorded.

3. How to call the Vue.js method when the page loads?

a89d2fadc413bdc14ebf6930c180a968.jpeg

We can call it when the page loads by calling the Vue.js method in the beforeMount component hook.

For example, we can write:

<template>
  <div id="app"></div>
</template>
<script>
export default {
  name: "App",
  methods: {
    getUnits() {
      //...
    },
  },
  beforeMount() {
    this.getUnits();
  },
};
</script>

Add the getUnits method to the methods attribute.

We call this.getUnits in the beforeMount hook.

this.getUnits is the getUnits method in the methods object property.

We can also run it on page load by calling the method in the created hook:

<template>
  <div id="app"></div>
</template>
<script>
export default {
  name: "App",
  methods: {
    getUnits() {
      //...
    },
  },
  created() {
    this.getUnits();
  },
};
</script>

We can do the same in the mounted hook:

<template>
  <div id="app"></div>
</template><script>
export default {
  name: "App",
  methods: {
    getUnits() {
      //...
    },
  },
  mounted() {
    this.getUnits();
  },
};
</script>

When using Vue.js to build an application, Vue.js will initialize components according to a certain life cycle order. In this initialization process, each component instance will go through some specific initialization and destruction processes in turn, and these processes are the life cycle of the component.

Vue.js provides some hook functions (also known as life cycle functions), which are executed in sequence at different stages of the component life cycle.

beforeMount, created and mounted are all hook functions of the Vue.js component life cycle. Their main differences and usage are as follows:

1. created hook function

The created hook function will be called immediately after the component instance is created. At this time, the data observation and event mechanism of the component have been initialized.

At this stage, we can perform some initialization operations, such as initializing the data of the component, setting the properties of the component, initializing the state of the component, and so on.

2. beforeMount hook function

The beforeMount hook function will be called after the template is compiled, but before it is mounted. At this stage, Vue.js has compiled the template of the component into a rendering function, and associated the rendering function with the component instance.

At this stage, we can perform some DOM operations, such as modifying the style, attributes, child elements, etc. of DOM elements. But it should be noted that the component has not been mounted on the DOM at this time, so some operations that need to obtain information such as the size and position of DOM elements should be executed in the mounted hook function.

3. mounted hook function

The mounted hook function will be called after the component is mounted on the DOM. At this stage, Vue.js has mounted the component instance to the specified DOM element and performed a rendering.

At this stage, we can access the DOM elements of the component, and perform some operations that need to access the DOM elements, such as getting the size and position of the DOM elements, and so on. In addition, the mounted hook function is also a good time to interact with third-party libraries, because the DOM elements have been rendered at this time.

In short, these three hook functions are hook functions of the Vue.js component life cycle. They are called after the component instance is created, after the template is compiled, before it is mounted, and after it is mounted, to perform different logical operations.

4. Perform certain operations when the Enter key is pressed in Vue.js

4c95f47430571a8929db6640e56df80c.png

We can do something when the enter key is pressed by adding a v-on:keyup directive to the element that does it.

For example, we can write the following code:

<template>
  <div id="app">
    <input v-on:keyup.enter="onEnter" />
  </div>
</template>
<script>
export default {
  name: "App",
  methods: {
    onEnter() {
      console.log("pressed enter");
    },
  },
};
</script>

We use the enter modifier to add the v-on:keyup directive to listen for the press of the enter key.

We set its value to the onEnter method so that it runs when the input box is focused and enter is pressed.

Also, we can use @ instead of v-on: to simplify the code a bit.

Specifically, we can write the following code:

<template>
  <div id="app">
    <input @keyup.enter="onEnter" />
  </div>
</template>
<script>
export default {
  name: "App",
  methods: {
    onEnter() {
      console.log("pressed enter");
    },
  },
};
</script>

No matter which example we use, when we focus on the input box and press enter, we should see "pressed enter" printed to the log.

5. How to display different content for mobile browsers in the application?

8be1a418f57a8ed08b4b80c668360d59.jpeg

Sometimes, we want to display different content for mobile browsers in Vue.js applications.

We can determine if a browser is a mobile browser by checking the browser's user agent and display content accordingly, displaying different content for mobile browsers in a Vue.js application.

For example, we can write:

<template>
  <div id="app">
    <div v-if="!isMobile()">desktop</div>
    <div v-else>mobile</div>
  </div>
</template>
<script>
export default {
  name: "App",
  methods: {
    isMobile() {
      return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
        navigator.userAgent
      );
    },
  },
};
</script>

We've added a method that checks the isMobile string property to see if it contains any mobile browser keywords.

Then in the template, we call the isMobile method in the v-if directive to determine whether the browser is a non-mobile device.

If not, display "desktop", otherwise use the v-else directive to display "mobile".

Also, we can check the width of the screen and display the content accordingly. For example, we can write:

<template>
  <div id="app">
    <div v-if="!isMobile">desktop</div>
    <div v-else>mobile</div>
  </div>
</template><script>
export default {
  name: "App",
  data() {
    return {
      isMobile: true,
    };
  },
  mounted() {
    this.onResize();
    window.addEventListener("resize", this.onResize, { passive: true });
  },
  methods: {
    onResize() {
      this.isMobile = window.innerWidth < 600;
    },
  },
  beforeDestroy() {
    if (typeof window !== "undefined") {
      window.removeEventListener("resize", this.onResize, { passive: true });
    }
  },
};
</script>

We use addEventListener to listen to the 'resize' resize event.

If it is triggered, then we run the onResize method and set the isMobile responsive property according to the screen size.

If window.innerWidth is less than 600, set it to true .

Otherwise, we set it to false .

In the beforeDestroy hook, we call
window.removeEventListener to remove the resize event listener.

Finish

Due to the limited space of the article, today’s content will be shared here. At the end of the article, I would like to remind you that the creation of articles is not easy. If you like my sharing, please don’t forget to like and forward it, so that more people in need See. At the same time, if you want to gain more knowledge of front-end technology, welcome to follow me, your support will be the biggest motivation for me to share. I will continue to output more content, so stay tuned.

Fan benefits

Share the source code of 9 commonly used TailwindCSS card templates, if you like it, download it and collect it

Guess you like

Origin blog.csdn.net/Ed7zgeE9X/article/details/132484971