Dynamically set vue instantsearch index-name

53 views Asked by At

I want to use the same HTML template for different pages but load in different Algolia indices based on the URL.

In my HTML template I can do this <div id="app" data-section="section"></div> where data-section is set dynamically by the CMS.

Then in main.js I have

import { createApp } from 'vue'
import App from './App.vue'
import InstantSearch from 'vue-instantsearch/vue3/es';

const container = document.getElementById('app');
const app = createApp(App, {
  section: container.dataset.section
});
app.use(InstantSearch);
app.mount('#app');

But then I'm not sure how to access that in App.vue which is set up like this:

<ais-instant-search
  :search-client="searchClient"
  index-name="???" // this should be set by the data-section attribute
>
…
</ais-instant-search>

import algoliasearch from 'algoliasearch/lite';
import 'instantsearch.css/themes/algolia-min.css';
import { AisPagination, AisMenuSelect } from 'vue-instantsearch/vue3/es';

export default {
  components: {
    AisPagination,
    AisMenuSelect
  },

  data() {
    return {
      searchClient: algoliasearch('xxxxxx','yyyyyy'),
    };
  },

  methods: {},
};
1

There are 1 answers

0
Tyssen On BEST ANSWER

I found my answer. What I needed to do was use provide on the parent:

main.js

const section = document.getElementById('app').dataset.section;
const app = createApp(App);
app.provide('section',section)
app.use(InstantSearch);
app.mount('#app');

and then in App.vue:

<ais-instant-search
  :search-client="searchClient"
  :index-name="indexName"
>

export default {
  inject: ['section'],

  data() {
    return {
      searchClient: algoliasearch('xxxxxxx','yyyyyyy'),
      indexName: this.section
    };
  },