Vue Custom Element Gutenberg Block
<?php | |
// NOTE: It would normally be recommended to split a block's JavaScript | |
// implementation to a separate file, but is authored here in a single | |
// file for convenience's sake. | |
// | |
// See: https://github.com/WordPress/gutenberg/pull/2791 | |
/** | |
* Plugin Name: Stars Block | |
*/ | |
function stars_enqueue_block_editor_assets() { | |
wp_register_script( | |
'vue', | |
'https://vuejs.org/js/vue.js' | |
); | |
wp_register_script( | |
'vue-custom-element', | |
'https://unpkg.com/vue-custom-element@1.3.0/dist/vue-custom-element.js', | |
array( 'vue' ) | |
); | |
wp_register_script( | |
'stars-block', | |
null, | |
array( 'wp-blocks', 'vue', 'vue-custom-element' ) | |
); | |
wp_enqueue_script( 'stars-block' ); | |
$script = <<<HTML | |
Vue.use( VueCustomElement ); | |
Vue.customElement( 'stars-block-edit', { | |
props: [ | |
'stars', | |
'setAttributes', | |
], | |
template: ` | |
<div> | |
<span v-for="n in 5"> | |
<span | |
@click="setAttributes( { stars: n } )" | |
:class="[ | |
'dashicons', | |
n > stars ? 'dashicons-star-empty' : 'dashicons-star-filled' | |
]" | |
/> | |
</span> | |
</div> | |
` | |
} ); | |
wp.blocks.registerBlockType( 'stars-block/stars', { | |
title: 'Stars', | |
icon: 'star-filled', | |
category: 'layout', | |
attributes: { | |
stars: { | |
type: 'number', | |
default: 1 | |
} | |
}, | |
edit: 'stars-block-edit', | |
save: function() {} | |
} ); | |
HTML; | |
wp_script_add_data( 'stars-block', 'data', $script ); | |
} | |
add_action( 'enqueue_block_editor_assets', 'stars_enqueue_block_editor_assets' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment