用Vue里面的setup函数做一个todolist代办事件清单实例

79 阅读1分钟
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script src="https://unpkg.com/vue@next"></script>
  </head>
  <body>
    <div id="root"></div>
  </body>
  <script>
    const app = Vue.createApp({
      // 模板
      //   里面的list的值来自于遍历v-for
      // list里面用到了v-for,都要加key
      template: `
      <div>
<div>
      <input  type="text" :value="inputValue"  @input="handleInputValueChange" />
      <button @click="handleClick">提交</button>
</div>
      <ul>
        <li v-for="(item,index) of list" :key="index">
            第{{index+1}}件事是{{item}}
            </li>
        </ul>
        </div>
        `,
      // setup函数
      setup() {
        // 要用到的vue方法
        const { reactive, ref } = Vue;
        // 新增代办事件先添加到数组list,然后遍历数组加到li里面
        // 这个数组要响应式的引用到页面,就要reactive包装一下,包装成对象
        const list = reactive([]);
        // 检测inputValue变化
        const handleInputValueChange = (e) => {
          // e是点击时候产生的对象,里面包括了各种东西
          // e.target是当前点击的元素,
          // 这里点击了input框
          const { reactive, ref } = Vue;
          inputValue.value = e.target.value;
        };
        // inputValue
        // 获取到input输入的值,要ref包装才能加到页面
        const inputValue = ref("");
        // handleClick
        const handleClick = () => {
          // 点击了提交按钮
          // inputValue就推到定义的空数组里面去
          //   inputValue已经被包装成对象了,所以要加.value
          list.push(inputValue.value);
          // 推进去以后,input框就变回空白了
          inputValue.value = "";
        };
        // handleInputValueChange
        //setup里面用到的都在setup函数里return出去
        return {
          list,
          inputValue,
          handleInputValueChange,
          handleClick,
        };
      },
    });
    const vm = app.mount("#root");
  </script>
</html>