vue3 学习-初识体验-常见指令v-for和v-model

继续通过小案例来体验一些常用的指令, 以经典的todolist进行展示. 首先呢通过 v-for 指令进行dom循环.

v-for

通常是在循环dom的编写的同时遍历数据进行填充.

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Document</title>
  <script src="https://unpkg.com/vue@3"></script>
</head>
<body>
  <div id="root"></div>
  <script>
    Vue.createApp({
      data () {
        return { 
          list: ['hello', 'world', 'vue', 'react'] 
        }
      },
      template: `
        <ul>
          <li v-for="(item, index) of list">{{item}} {{index}}</li>
        </ul>
        `
    }).mount('#root')
  </script>
</body>
</html>

则显示结果如下:

* hello 0
* world 1
* vue 2
* react 3

v-model

用来对输入框的值和数据进行双向绑定 (共用一个数据)

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Document</title>
  <script src="https://unpkg.com/vue@3"></script>
</head>
<body>
  <div id="root"></div>
  <script>
    Vue.createApp({
      data () {
        return { 
          inputValue: '',
          list: [] 
        }
      },
      methods: {
        addItem () {
          this.list.push(this.inputValue)
          this.inputValue = ''
        }
      },
      template: `
      <div>
        <input v-model="inputValue" />
        <button @click="addItem">增加</button>
        <ul>
          <li v-for="(item, index) of list">{{item}} {{index}}</li>
        </ul>
      </div>
        `
    }).mount('#root')
  </script>
</body>
</html>

对于 v-for 的使用是极高频的, 但其实只需要了解其语法就可以了, 仅从工具使用的角度; 对于 v-model 同理, 理解输入框的值和数据用的值都用一个 inputValue 变量进行双向绑定, 或者说共享吧.这个特别高效. 以前用原生 js 来弄还是比较麻烦的, 又要处理 dom 又要处理数据. 通过 vue 这种工具就极大降低了开发的难度, 而且还特别好用.

posted @ 2022-08-22 23:24  致于数据科学家的小陈  阅读(147)  评论(0编辑  收藏  举报