简体   繁体   中英

vuejs - how to pass data to webpacked root instance

I have an application where I'm using Single File Components for showing data in a table. The data is queried based on a search string and columns that I want to include in the results (the data is fetched by basically an ajax request).

My goal is to create a reusable component so that I can pass the query text and the column names to the component. Normally I could use props and slots for this, but since I'm using Single File Components I have no idea how to pass data to the component.

The " public " interface to the Single File Component looks as follows:

<!-- index.hmtl -->
<div id="app"></div>
<script src="./build/webpackedComponent.js"></script>

// main.js / Component entry point
import Vue from 'vue'
import App from './components/app.vue'

new Vue({
  el: '#app',
  render: h => h(App)
})

Inside App I need the data for the ajax request. An idea I had was to import a json file in the main entry point of the component, but then I would have to repack the component everytime I change the json, and for multiple uses of the component, I need to pack them each time for every instance that uses different data...

Any ideas?

Find your webpack.base.conf.js file (in my project it is located inside the build folder) or the equivalent configuration file, then add library: 'myLibrary' to the output object.

(should end up with something like this:)

module.exports = {
  entry: {
    app: ['./src/main.js']
  },
  output: {
    library: 'myLibrary',
    path: config.build.assetsRoot,
    publicPath: process.env.NODE_ENV === 'production' ? config.build.assetsPublicPath : config.dev.assetsPublicPath,
    filename: '[name].js'
  },
  .
  .
  .

then in main.js, you can export Vue like this:

// main.js / Component entry point
import Vue from 'vue'
import App from './components/app.vue'

export { Vue, App };

And now in the global scope you can do this:

new myLibrary.Vue({
  el: '#app',
  data: {
    value1: 12,
    value2: 14
  },
  components: { App: myLibrary.App },
  template: '<App :prop1="value1", :prop2="value2"></App>'
});

That is, whatever you export in main.js will be accessible to the global scope via the name of the library you provided in your webpack config file... in this case, myLibrary .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM