2

As the title reads, should I declare all my variables in data? Or only the ones used for data-binding?

<script>
    var somethingElse = '';    //should this be declared here?
    export default {
    data () {
        return {
            something: '',     //this var will be used in data-binding
            somethingElse: ''  //or here?

        }
    }

...

1 Answer 1

5

I understand you come from other libs/frameworks, where there's difference in instance variables and state. Where changing instance variables doesn't trigger re-renders, but changing the state might.

In Vue you don't have to worry about that. You can have everything in data, and Vue will only re-render if you change something that is actually used anywhere that matters (e.g. the template).

<script>
    export default {
    data () {
        return {
            something: '',     
            somethingElse: '' // you can declare it here, it's the usual way
        }
    }

...

On the other hand, you could declare the variable outside, but if you do:

<script>
    var somethingElse = ''; // this will be a singleton. Generally used for constants
    export default {
    data () {
        return {
            something: '',     //this var will be used in data-binding
        }
    }

...

Then somethingElse will be shared among all instances of this component. It will be sort of a singleton value for all of them: if you change in one, it will change for all instances at the same time. (And it won't be reactive, meaning a change to somethingElse won't trigger a re-render anywhere.)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.