Home > Software engineering >  Why the function execute immediately in vue 3 setup block
Why the function execute immediately in vue 3 setup block

Time:02-04

I define a function in vue 3 like this:

setup(props) {
    
    const { getters } = useStore();

    const add = () => {
      alert("dd");
    };

    return (
      add
    );
  }

and invoke it in the template like this:

<button type="button"  @click="()=>add">
        <span ></span>
      </button>

now I found the setup function add execute when the component created. why the add function execute immediately? how to avoid it execute automatically? I have tried to write the function invoke like this:

@click="()=>add"

seems did not work. This is the code how I mount the component:

export async function addTransShowElement(translation:string){
  let anchorElementId = "uniq-anchor-point";
  let anchorElement = document.getElementById(anchorElementId);
  if (anchorElement == null || anchorElement === undefined) {
    let reddwarfTranslateDiv = document.createElement("div");
    reddwarfTranslateDiv.id = anchorElementId;
    document.body.appendChild(reddwarfTranslateDiv);
  }
  let appElement = document.getElementById("reddwarf-translate-app");
  if (appElement == null || appElement === undefined) {
    let props = {
      word: translation.toString().trim(),
    };
    const app = createApp(TranslatorPop, props);
    app.use(store);
    let vm = app.mount("#uniq-anchor-point");
    document.body.appendChild(vm.$el);
  }
}

CodePudding user response:

Try like in snippet return object not function:

const App = {
  setup() {
    const add = () =>  alert("dd");
    return {   //           
  •  Tags:  
  • Related