user3160178
user3160178

Reputation: 81

WordPress Vue Plugin with single file component - cannot use import

I'm new to WP and Vue.js I'm trying to create a plugin for WP in Vue that takes data from WP API and print a simple table.

Here's my plugin files:

custom_plugin_name.php

<?php

/**
 * Plugin Name: custom_plugin_name
 * Description: WordPress Vue.js plugin
 * Version: 1.0
 */


// Register API Endpoints
[...]


// Register scripts
function func_load_vuescripts() {
    // Register Vue.js and scripts
    wp_register_script('wpvue_vuejs', 'https://cdn.jsdelivr.net/npm/vue/dist/vue.js');
    wp_register_script('my_vuecode', plugin_dir_url( __FILE__ ) . 'vuecode.js', 'wpvue_vuejs', true );
}
add_action('wp_enqueue_scripts', 'func_load_vuescripts');


// Create shortscode function
function func_wp_vue() {

    // Load Vue.js and scripts
    wp_enqueue_script('wpvue_vuejs');
    wp_enqueue_script('my_vuecode');

    return file_get_contents(plugin_dir_path(__FILE__) . './App.vue');
}

// Add shortscode
add_shortcode( 'wpvue', 'func_wp_vue' );

vuecode.js

import App from './App.vue'

var app = new Vue({
    el: '#vuejs-container',
    template: '<App/>',
    components: { App }
})

App.vue

<template>
    <div id="vuejs-container">
        <h1>My Todo App!</h1>
        <AppTable/>
    </div>
</template>

<script>
    import AppTable from "./components/Table.vue";

    export default {
        components: {
            AppTable
        }
    };
</script>

When I run this code I get two errors on the two import statements (in vuecode.js and App.vue):
Uncaught SyntaxError: Cannot use import statement outside a module

I've even try to include vuecode.js script with type="module" attribute but doesn't change anything.

Upvotes: 0

Views: 1142

Answers (1)

Mathias Nicod
Mathias Nicod

Reputation: 130

You need to import all of your vue components in the vuecode.js file. Also, make sure to specify all your components when instancing your vue.js app.

import App from './App.vue'
import AppTable from './components/Table.vue';

var app = new Vue({
    el: '#vuejs-container',
    template: '<App/>',
    components: { 
        App,
        AppTable
    }
})

Upvotes: 1

Related Questions