1

Is it possible to declare and pass a data-attribute value from a html tag of the Vue instance, and then have it available in the data object?

index.html:

<div id="app" data-title="My app title"></div>

App.vue:

data () {
  return {
    appTitle: // whatever is declared in data-title
  }
}
0

3 Answers 3

2

This code works for me:

index.html:

<div id="app" data-id="123"></div>

index.js:

(function (el) {

    new Vue({
        el,
        render: h => h(Module),
        data: () => Object.assign({}, el.dataset) ,
    });

})(document.getElementById('app'));

Module.vue:

export default {
    name: 'Module',
    data() {
        return {
            id: this.$parent.id,
        };
    },
};
Sign up to request clarification or add additional context in comments.

Comments

1

Yes it is:

data () {
  return {
    appTitle: document.getElementById('app').dataset.title
  }
}

However, it is possible that the DOM is not available on component initialization. So you should probably put that code into the mounted hook of your component:

<script>
    export default {
        data () {
            return {
                appTitle: null
            }
        },
        mounted () {
            this.appTitle = document.getElementById('app').dataset.title
        }
    }
</script>

2 Comments

Even if I declare the data-title tag, it is reset when Vue renders. So this returnes undefined.
I see - it's probably because of my structure. I have my Vue init inside a separate main.js file - and rest is done in App.vue
0

Here's a different approach that doesn't rely on the DOM API, but cannot be used to get data-attributes from the root (#app) element:

{
    el: '#app',
    template: `
        <div ref="mydiv" data-attribute="data attribute">
            Hello from template
            <div>
                Hello from {{attribute}}
            </div>
        </div>`,
    data(){
        return {
          attribute: ''
        }
    },
    mounted(){
        this.$data.attribute = this.$refs.mydiv.dataset.attribute;
    }
});

Here's a pen with a working example

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.