vue realizes the selection effect

  • 2021-08-28 19:22:47
  • OfStack

Previously

I haven't written Vue for a long time, and I'm a little rusty. This thing still needs to be used more.

When you see a demand in the afternoon, select the photo album picture as the carousel picture. The interface returns a list of photo albums, and the user selects 1 and throws it back.

I knew it wasn't easy until I saw e. target. className. .

Vue is data driven

Data-driven this is what I think is different from jQuery.

jQuery is point 1, add class and move class.

Vue is point 1, data is recorded, and then automatically notifies the view.

One is to save the selected state in DOM, and the other is to save the selected state in js data model.

So when I saw the behavior of using Vue and then obtaining DOM to change class, I stopped him in time. In other words, you have done it yourself. Why do you want Vue? . .

What happens to data-driven and previous ideas in 1?

Data-driven is a process from data to view, if you only change the view without changing the data. Then he refreshes the data somewhere else, which may cause the view to be out of sync. For example, if you write it when you write it, you may not read it when you read it. Why is this so? Because there are two places can be changed ah, Vue DOM deleted, the new rendering does not have the status you write, read a ghost when reading. Think about it, can this one chance thing work well?

How does Vue achieve this effect

After all that nonsense, let's go to the address first, the portal-I wrote DEMO "the specific code is here."

Let's briefly talk about the ideas of three writing methods

The selected id is made into an array and one queue is maintained. : class = "{selected: ~ checkSelect (item. id)}" When rendering, determine if there is an id in the array. The selected id is made into one object, and one more object is maintained. : class= "{selected: selectList [item. id]}" Compared to the first one, id is much easier to find as key. What should be noted here is. $set, which should be tested with emphasis. Change the original object directly and add one more parameter. This is not recommended.

Related articles: