Search code examples
wordpressvue.jsvuex

Passing initial values from wordpress to vuex


I am working on building a custom taxonomy landing page on a wordpress site using vuejs. I am using vuex for state management but am currently stuck with a problem. for few variable like "slug" I don't know how to pass initial value to the store. I am using wp_localize_script to send value from wordpress but vuejs does not recognize the variable.

Archive.php

wp_register_script( 'archive-vue-chunk', THEME_JAVASCRIPT_URI . '/archive_js/dist/assets/chunk-vendors.js',array('site-2017'),null,true);
wp_register_script( 'archive-vue', THEME_JAVASCRIPT_URI . '/archive_js/dist/assets/app.js',array('archive-vue-chunk'),null,true);
$term  = get_queried_object();
$slug  = $term->slug; 

wp_localize_script ( 'archive-vue', 'initialvaluestovue', array (
    'ajaxurl' => admin_url ( 'admin-ajax.php' ),
    'slug'    => $slug 
    ) );

main.js


import Vue from 'vue'
import Archive from './Archive.vue'
import store from './store'


Vue.config.productionTip = false 

new Vue({
  store,
  render: h => h(Archive),
  propsData:{ initialvaluestovue }
}).$mount('#archive_using_vuejs')

Any help is very much appreciated. Thank you


Solution

  • I changed main.js to as follows and was able to get the value in Archive.vue

    main.js

    new Vue({
    store,
     render: h => {
       const context = {
       props: {
         initialvaluestovue : window.initialvaluestovue
       }
     };
     return h(Archive, context)
    }   
    }).$mount('#archive_using_vuejs')
    

    I was able to display the pass object in archive.vue

    Archive.vue

    <template>
    <div class="layout">{{initialvaluestovue}}</div>
    </template>
    
    
    <script>
    export default {
    name: 'Archive',    
    props:{
        initialvaluestovue:{
            type: Object
        }
     }
    }
    </script>