3

So I'm just starting to play with Vue.js and I would like to know if there is a nice way to initialize the data object with html tags content from the page.

Basically I have a page that displays information and I would like to turn it into a tiny Vue application to avoid having a separated edit page. So I added the form with 2 way binding which submits the values via ajax.

The thing is I really want to avoid Flash Of Uncompiled Content, but then I feel like I have to duplicate all my data, once in the html tag, once in the data object.

<div id="app">
  <span v-text="prop1">This is filled by the backend</span>
  <input v-model="prop1" type="text" v-cloak />
</div>

<script>
new Vue({
    el: "#app",
    data: {prop1: "This is filled by the backend..again"}   // << Can I avoid this?
});
</script>

Could I tell Vue to get the data from the html tags since it's already there?

Thanks!

1
  • Instead of having backend dynamically generate scripts, you can put the initial json serialized data into a prop of a vue component. Commented Nov 6, 2015 at 19:43

1 Answer 1

1

You are looking for props

Your html element would look something like <custom-element dataToPass="dataFromHtml"></custom-element>. Then you can access it in your vue instance via this.dataToPass.

Have a read through the documentation, there is a difference if you pass a string or an expression (from another vue instance for example).

In your example:

<div id="app">
      <span prop1="{ backendVariable}" v-text="prop1"></span>
      <input v-model="prop1" type="text" v-cloak />
</div>

<script>
    new Vue({
        el: "#app",
        props: ['prop1']
    });
</script>

```

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.