vue3写法

vue2写法
image.png
handleClick根据传进来的i来判断调用add,edit,delete方法

由于vue3的setup里面this没有vue实例
image.png
在获取变量后应该怎么调用对应的函数呢?(除了用if else判断)

阅读 2.8k
2 个回答

把函数挂载到一个对象上,取的时候使用对象取

const handleClick = (name) => {
    fns['handle' + name]
}

const fns = {
    eventName,
    handleClick,
    handAdd
}

return fns

https://codepen.io/pantao/pen...

如果想把 addedit以及 delete 写进 methods 里面,那就使用以前的方式,把 handleClick 也写进去,否则,就把这些全写进 setup 里面

<template>
  <div id="app">
    <p>
      Learn more with the
      <a
        href="https://vuejs.org/"
        target="_blank"
        rel="noopener"
      >Vue Docs &amp; Resources</a>.
    </p>

    <button @click="handleClick('add')">Add</button>
    <button @click="handleClick('edit')">Edit</button>
    <button @click="handleClick('delete')">Delete</button>
  </div>
</template>

<script>
export default {
  setup() {
    const actions = {
      add: () => alert('新增~'),
      edit: () => alert('编辑~'),
      delete: () => alert('删除~'),
    }
    
    const handleClick = (act) => {
      actions[act]()
    };
    
    return {
      handleClick
    }
  }
};
</script>

<!-- Use preprocessors via the lang attribute! e.g. <style lang="scss"> -->
<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}

a,
button {
  color: #4fc08d;
}

button {
  background: none;
  border: solid 1px;
  border-radius: 2em;
  font: inherit;
  padding: 0.75em 2em;
}
</style>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题