getElementsByClassName in context of vue

2019-08-23 02:41发布

问题:

In the context of vue.js, how does getElementsByClassName work?

I have the following snippet of code below - the goal is to click a button and change the color of the h1 tag to green using vue.js methods:

<html>
    <head>
        <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script>
    </head>
    <body>
    <div id="app">
        <h1 class="main-header">{{ message }}</h1>
        <button v-on:click="colorChange">Click me</button>
    </div>
    <script>
        var app = new Vue({
        el: '#app',
            data: {
                message: 'Hello Vue!'
            },
            methods: {
                colorChange: function() {
                    // what do I do here...?
                }
            }
        })
    </script>
    </body>
</html>

It's to my understanding that Vue is like React with a virtual DOM and you don't modify it directly.

Obviously in vanilla JS you just do document.getElementsByClassName('main-header')[0].style.backgroundColor="green"; but that seems counterintuitive in Vue.

Am I overcomplicating this and is this in fact how it works? Or does Vue have a specific way of handling this? I've been looking at https://vuejs.org/v2/guide/class-and-style.html but it just explains how to bind classes. I'm also reading through https://vuejs.org/v2/guide/events.html but I'm having a hard time finding what I need in regards to targeting an element/modifying it in some way...

How do you select and/or modify an element in the context of Vue?

回答1:

You are correct. In Vue, interacting directly with the DOM is counter-intuitive.

Fortunately, there is a directive that allows you to apply style changes directly by binding to a data property. (Keep in mind, you could do something similar with a class as well).

<h1 class="main-header" v-bind:style="{ color: activeColor}">{{ message }}</h1>
<button v-on:click="colorChange">Click me</button>

In your component, create a data property and update it on button click:

data: {
    message: 'Hello Vue!',
    activeColor: 'red'
},
methods: {
    colorChange: function() {
        this.activeColor = 'green'
    }
}