Last active
February 15, 2022 04:13
-
-
Save aduth/369767f8153eaad1d955a8022f14ec34 to your computer and use it in GitHub Desktop.
Vue Custom Element Gutenberg Block
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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/[email protected]/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