L
L
LionG2020-06-27 12:46:11
Vue.js
LionG, 2020-06-27 12:46:11

How to get attributes from outerHTML as props when instantiating Vue?

In theory it should work like this:

<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app" :sometext="'hello world'"></div>
<script type="text/javascript">
new Vue({
  props: ['sometext'],
  mounted: function () {
    console.log(this.sometext)
  }
}).$mount('#app')
</script>


However, undefined is thrown into the console.

There is an option to manually load data from attributes, but in my opinion this is some kind of crutch and should work differently.
beforeMount: function () {
    this.sometext = this.$el.attributes.sometext.value
  },

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dima Polos, 2020-06-27
@dimovich85

You are trying to hang vue directives on the root node in html, so it doesn't work. You can make it data-sometext="blabla", and then try to read the attributes of this DOM node through $el. Only this whole idea looks like a crutch, do you really need to send data to the root element? Inside components down the tree from the root component, props will work without problems.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question