Mod Creation/Reusable Components with PetiteVue: Difference between revisions

no edit summary
No edit summary
No edit summary
Line 226: Line 226:
   content: { lines: ['My first paragraph.', 'My second paragraph.'] }
   content: { lines: ['My first paragraph.', 'My second paragraph.'] }
}), document.getElementById('woodcutting-container'));</nowiki>
}), document.getElementById('woodcutting-container'));</nowiki>
=== Programmatically Manipulating Components ===
If you need to programmatically manipulate a component's (or store's) state, save the reference to the <code>props</code> object being passed into <code>ui.create</code>. The state should only be manipulated through methods on the object, not directly setting properties.
For example, using our <code>Counter</code> from above:
<nowiki><!-- templates.html -->
<template id="counter-component">
  <span class="text-light">{{ count }}</span>
  <button class="btn btn-secondary" @click="inc">+</button>
</template></nowiki>
<nowiki>// setup.mjs
function Counter(props) {
  return {
    $template: '#counter-component',
    count: props.count,
    inc() {
      this.count++;
    }
  };
}
export function setup({ onInterfaceReady }) {
  onInterfaceReady(() => {
    // Save a reference here
    const counter = Counter({ count: 0 });
    ui.create(counter), document.getElementById('woodcutting-container'));
    // Manipulate here to reflect changes in the UI
    // BAD: counter.count++;
    // GOOD:
    counter.inc();
  });
}</nowiki>
89

edits