Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to initialise an app with data in vuejs

I'm using a single file component called Foo:

<template>
<div>
  This is the app. X  is {{ x }}, y is {{ y }}
</div>
</template>
<script>
export default {
  data() {
   return { x: 'hello x' };
  },
}
</script>

And I'm initializing my app like:

// somewhere here 'node' gets set to a DOM node,
// and 'y' is created.
import Vue from 'vue';
import Foo from './Foo.vue';
const app = new Vue({             
  'el': node,                     
  data: {y},
  render: h => h(Foo)             
});                               

This is an oversimplification in that 'y' is actually an object not just a simple string. If that makes a difference.

I know how to pass props etc for child components, but I'm struggling to get the main config data into the top level Vue app!

like image 922
artfulrobot Avatar asked Nov 25 '25 08:11

artfulrobot


2 Answers

Foo.vue :

add props:['y']

<template>
<div>
  This is the app. X  is {{ x }}, y is {{ y }}
</div>
</template>
<script>
  export default {
  props:['y']
    data() {
      return {
        x: 'hello x'
      };
    },
  }
</script>

main.js

add template:'<Foo :y="y"'/> to the vue instance and node should be a valid html element

// somewhere here 'node' gets set to a DOM node,
// and 'y' is created.
import Vue from 'vue';
import Foo from './Foo.vue';
const app = new Vue({
  'el': node,
  data: {
    y: "some content"
  },
  template: "<Foo :y='y'/>"
});
like image 134
Boussadjra Brahim Avatar answered Nov 26 '25 20:11

Boussadjra Brahim


Here's how I did it.

In Foo.vue add props:

<template>
<div>
  This is the app. X  is {{ x }}, y is {{ y }}
</div>
</template>
<script>
export default {
  data() {return { x: 'hello x' };},
  props: [ 'y' ],
}
</script>

Then in the main js that creates the app:

// somewhere here 'node' gets set to a DOM node,
// and 'y' is created.
import Vue from 'vue';
import Foo from './Foo.vue';
const app = new Vue({             
  'el': node,
  render: h => h(Foo, {props: {y})
});                               

This way y gets passed in as a prop, but without resorting to using template which requires the heaviere compiler-included Vue build.

The advantage of this is that my CMS can spit out chunks of the page that should each be Vue apps, can include configuration for each of those apps, and can thten create all the Vue apps which differ only in their content.

While the focus of documentation on single file components seems to be a monolithic single page app, that's not what I needed.

like image 23
artfulrobot Avatar answered Nov 26 '25 21:11

artfulrobot



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!