English 中文(简体)
Vue.js change class on mounted
原标题:

I have a button element with a .hover property and I need the hover animation to also happen as soon as the page is mounted. How can I attribute a class to a button on the mounted function and then disattribute it?

I was thinking of using a setTimeout but it s not working properly. I m basing my code off of this codePen: https://codepen.io/lucasfads/pen/QWwjGjv

<a href="#" class="button" id="specialButton">
  <span class="icon"></span>
  <span class="text">Hakuna Matata</span>
</a>
mounted() {
  document.getElementById("specialButton").classList.add("expanded");

  setTimeout(() => {
    document.getElementById("specialButton").classList.remove("expanded");
  }, 3000);
}
.button {
  background-color: #099;
  color: white;
  text-decoration: none;
  border-radius: 60px;
  height: 32px;
  display: inline-flex;
  align-items: center;
  overflow:hidden;
  width: auto;
  max-width: 32px;
  transition: max-width 0.5s;
}

.button:hover,
.button .expanded {
  max-width: 300px;
}

.icon {
  font-family: "Font Awesome 5 Free";
  font-size: 16px;
  margin-right: 15px;
  padding: 0px 8px;
  display: flex;
  align-items: center;
}

.text {
  white-space: nowrap;
  padding-right: 15px;
}
问题回答

It should be .button.expanded not .button .expanded

Other than that, see a comment from Jaromanda X, I agree that using direct DOM manipulations in Vue is a bad indicator.

Another thought - it ll probably be more efficient to have that class by default, and then remove it later. Otherwise you mount, add class, remove class - 3 DOM operations. Instead you can just mount, remove class - 2 DOM operations.





相关问题
CSS working only in Firefox

I am trying to create a search text-field like on the Apple website. The HTML looks like this: <div class="frm-search"> <div> <input class="btn" type="image" src="http://www....

image changed but appears the same in browser

I m writing a php script to crop an image. The script overwrites the old image with the new one, but when I reload the page (which is supposed to pickup the new image) I still see the old one. ...

Firefox background image horizontal centering oddity

I am building some basic HTML code for a CMS. One of the page-related options in the CMS is "background image" and "stretch page width / height to background image width / height." so that with large ...

Separator line in ASP.NET

I d like to add a simple separator line in an aspx web form. Does anyone know how? It sounds easy enough, but still I can t manage to find how to do it.. 10x!

热门标签