Skip to content

Instantly share code, notes, and snippets.

@daliborgogic
Last active August 19, 2024 18:07
Show Gist options
  • Save daliborgogic/61c9c435244828563bd02f9dcad40dae to your computer and use it in GitHub Desktop.
Save daliborgogic/61c9c435244828563bd02f9dcad40dae to your computer and use it in GitHub Desktop.
Gutenberg Block built with Vue.js
// https://wordpress.org/gutenberg/
(wp => {
const el = wp.element.createElement
const __ = wp.i18n.__
wp.blocks.registerBlockType( 'plugins/gutenvue', {
title: __('Gutenberg: VueJS', 'gutenvue'),
category: 'widgets',
supportHTML: false,
attributes: {
who: {
selector: 'p',
attribute: 'who'
}
},
edit: props => {
const attributes = props.attributes
const setAttributes = props.setAttributes
const className = props.className
const focus = props.focus
const id = props.id
// Define id to mount VueJs app into
const vueAppIdAttr = 'vuetest-' + id
// Set default for who we're saying who to.
if (!attributes.hasOwnProperty('who')) {
attributes.who = 'Dlbr'
}
// Create copy of attributes to create intial state of Vue app with
let vueInitialState = {}
Object.keys(attributes).forEach(key =>
vueInitialState[key] = attributes[key]
)
// Create Vue app
const APP = new Vue({
// Mount on element we're about to create with el()
el: '#' + vueAppIdAttr,
data () {
return vueInitialState
},
// Use watchers to update
watch: {
who (newValue) {
setAttributes({who:newValue})
}
},
// Template for Vue app
template: '<div><p>who: {{who}}</p><input v-model="who"/></div>'
})
// Return using WordPress createElement
return el (
'div',
{className},
[
el(
'p',
{
className,
who: attributes.who
},
el(
'div',
{id: vueAppIdAttr}
)
)
]
)
},
save (attributes,className) {
el('p', {
className,
who: attributes.who
})
}
}
)
})(window.wp)
@daliborgogic
Copy link
Author

daliborgogic commented Jul 31, 2018

// functions.php
<?php
  function gutenvue () {
    wp_register_script(
        'gutenvue',
        plugins_url( 'plugins/gutenvue.js', __FILE__ ),
        array( 'wp-blocks', 'wp-element' )
    );

    register_block_type( 'gutenvue', array(
        'editor_script' => 'gutenvue',
    ) );
  }
  add_action( 'init', 'gutenvue' );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment