Categories
Vue Answers

How Rerun Vue Component mounted() Method in a Vue Component?

Sometimes, we want to rerun the code in the Vue component’s mounted method.

In this article, we’ll look at how to rerun the code in the Vue component’s mounted method.

Rerun Vue Component mounted() Method

To rerun the code that we wrote in the mounted method, we can move the code into its own method.

Then we can call that in mounted or anywhere else.

For instance, we can write:

new Vue({
  methods: {
    init(){
      //...
    }
  },
  mounted(){
    this.init();
  }
})

Then we can write:

<button @click="init">reset</button>

We set the init method as the click handler and also run it in the mounted hook.

Now we can reuse it as we wish.

Conclusion

To rerun the code that we wrote in the mounted method, we can move the code into its own method.

Categories
Vue Answers

How to Run the Vue.js Dev Server via HTTPS?

Sometimes, we want to run the Vue CLI dev server via HTTPS.

In this article, we’ll look at how to run the Vue CLI dev server via HTTPS.

Run Vue.js Dev Server with HTTPS

We can change the Vue dev server’s config to serve the project over HTTPS rather than HTTP.

To do that, we read the private key and certificate.

And we set the URL to serve the project on.

For instance, we can write:

const fs = require('fs')

module.exports = {
  devServer: {
    https: {
      key: fs.readFileSync('./certs/key.pem'),
      cert: fs.readFileSync('./certs/cert.pem'),
    },
    public: 'https://localhost:8888/'
  }
}

We read in the files and set them as the properties of the https property.

To make a certificate, we can use the mkcert program to do it.

We can install it on Windows, Mac OS, or Linux by following the instructions on https://github.com/FiloSottile/mkcert.

Then we can create a new key and certificate by running:

mkcert -install

and:

mkcert example.com "*.example.com" example.test localhost 127.0.0.1 ::1

Then we created a certificate valid for localhost.

We just copy the files to the cert folder and rename them to match what we have in the config.

Then we can run npm run dev and serve the project.

Conclusion

We can change the Vue dev server’s config to serve the project over HTTPS rather than HTTP.

Categories
Vue Answers

How to Open a Link in a New Tab with Vue Router?

Sometimes, we want to open a link in a new window with Vue Router.

In this article, we’ll look at how to open a link in a new window with Vue Router.

Open a Link in a New Tab with Vue Router

We can open a link in a new tab with Vue Router.

For instance, we can write:

const routeData = this.$router.resolve({ name: 'foo', query: { data: "bar" }});
window.open(routeData.href, '_blank');

We call the this.$router.resolve method to get the URL to open.

Then we call window.open to open the given URL.

The first argument is the URL.

'_blank' indicates that we open the URL in a new tab.

Conclusion

We can open a link in a new tab with Vue Router.