Skip to content

Instantly share code, notes, and snippets.

@ediamin
Last active February 28, 2019 15:19
Show Gist options
  • Save ediamin/eb7923456033f8784b4d43cd4849ab10 to your computer and use it in GitHub Desktop.
Save ediamin/eb7923456033f8784b4d43cd4849ab10 to your computer and use it in GitHub Desktop.
Vue.js design pattern to mimic WordPress' do_action
// Added at the bottom of Bootstrap.js
// wepos.hooks is the @wordpress/hooks package
wepos.addFilter = (hookName, namespace, component) => {
wepos.hooks.addFilter( hookName, namespace, ( components ) => {
components.push(component);
return components;
} );
};
// This snippets must be included AFTER Bootstrap.js and BEFORE rendering Home.vue.
// For example this could be in frontend/main.js
import HomeSampleListOne from 'frontend/components/HomeSampleListOne.vue';
import HomeSampleListTwo from 'frontend/components/HomeSampleListTwo.vue';
import HomeBeforeItemsWrapper from 'frontend/components/HomeBeforeItemsWrapper.vue';
// the follwing `weposHomeSampleList` and `weposHomeBeforeItemsWrapper` hooknames are
// used in $data properties in Home.vue
wepos.addFilter('weposHomeSampleList', 'weposHome', HomeSampleListOne);
wepos.addFilter('weposHomeSampleList', 'weposHome', HomeSampleListTwo);
wepos.addFilter('weposHomeBeforeItemsWrapper', 'weposHome', HomeBeforeItemsWrapper);
<template>
<div id="wepos-main" v-cloak v-hotkey="hotkeys">
...
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
<component
v-for="(component, index) in sampleLists"
:key="index"
:is="component"
/>
</ul>
<component
v-for="(component, index) in beforeItemsWrapper"
:key="index"
:is="component"
:products="getFilteredProduct"
/>
...
</div>
</template>
<scripts>
export default {
...
data() {
...
// Add an empty array so that, by default Vue has nothing to render
sampleLists: wepos.hooks.applyFilters( 'weposHomeSampleList', [] ),
beforeItemsWrapper: wepos.hooks.applyFilters( 'weposHomeBeforeItemsWrapper', [] ),
},
...
};
</scripts>
<template>
<li>From HomeSampleListOne.vue</li>
</template>
<script>
export default {};
</script>
<template>
<li>From HomeSampleListTwo.vue</li>
</template>
<script>
export default {};
</script>
<template>
<div>
component with div wrapper root
<pre>{{ products }}</pre>
</div>
</template>
<script>
export default {
props: {
products: {
type: Array,
required: true
}
}
};
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment