Skip to content

Instantly share code, notes, and snippets.

@Shelob9
Last active January 16, 2018 09:07
Show Gist options
  • Save Shelob9/86c97cfb4c7d92f9e2465d3f46ba1372 to your computer and use it in GitHub Desktop.
Save Shelob9/86c97cfb4c7d92f9e2465d3f46ba1372 to your computer and use it in GitHub Desktop.
Example WordPress block using VueJs, just to prove it works to Zac. Would be better to use https://github.com/alkin/vue-react or https://github.com/SmallComfort/react-vue
( function( wp ) {
var el = wp.element.createElement;
var __ = wp.i18n.__;
wp.blocks.registerBlockType( 'vuetest/vuetest', {
title: __( 'Vue Test', 'vuetest' ),
category: 'widgets',
supportHTML: false,
attributes: {
hi: {
selector: 'p',
attribute: 'hi',
},
},
edit: function( props ) {
//edit( { attributes, setAttributes, className, focus, id } )
var attributes = props.attributes,
setAttributes= props.setAttributes,
className = props.className,
focus = props.focus,
id = props.id;
//Define id to mount VueJs app into
var vueAppIdAttr = 'vuetest-' + id;
//Set default for who we're saying hi to.
if( ! attributes.hasOwnProperty( 'hi' ) ){
attributes.hi = 'Roy'
}
//Create copy of attributes to create intial state of Vue app with
var vueInitialState = {};
Object.keys( attributes ).forEach( function (key) {
vueInitialState[key] = attributes[key];
});
//create Vue app
var APP = new Vue({
//mount on element we're about to create with el()
el: '#' + vueAppIdAttr,
data: function () {
return vueInitialState
},
//Use watchers to update React
watch: {
hi: function (newValue) {
setAttributes({ hi:newValue});
}
},
//template for Vue app
template: '<div><p>HI: {{hi}}</p><input v-model="hi" /></div>',
});
//return using React/WordPress createElement
return el(
'div',
{ className: className },
[
el(
'p',
{
className:className,
hi: attributes.hi
},
attributes.hi
),
el(
'div',
{
id: vueAppIdAttr
},
),
]
);
},
save: function(attributes,className) {
el(
'p',
{
className:className,
hi: attributes.hi
}
);
}
} );
} )(
window.wp
);
<?php
function vuetest_enqueue_block_editor_assets() {
$dir = dirname( __FILE__ );
$block_js = 'vuetest/block.js';
$editor_css = 'vuetest/editor.css';
wp_register_script( 'vue', 'https://cdn.jsdelivr.net/npm/vue' );
wp_enqueue_script( 'vuetest-block', plugins_url( $block_js, __FILE__ ), array(
'wp-blocks',
'wp-i18n',
'wp-element',
'vue'
), filemtime( "$dir/$block_js" ) );
wp_enqueue_style( 'vuetest-block', plugins_url( $editor_css, __FILE__ ), array(
'wp-blocks',
), filemtime( "$dir/$editor_css" ) );
}
add_action( 'enqueue_block_editor_assets', 'vuetest_enqueue_block_editor_assets' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment