v-for/v-if 联合使用

以上实例联合使用 v-for/v-if 给 select 设置默认值:

<!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="app">
      <select @change="changeVal($event)" v-model="selOption">
        <template
          v-for="(site, index) in sites"
          :site="site"
          :index="index"
          :key="site.id"
        >
          <!-- 索引为 1 的设为默认值,索引值从0 开始-->
          <option v-if="index==1" :value="site.name" selected>
            {{site.name}}
          </option>
          <option v-else :value="site.name">{{site.name}}</option>
        </template>
      </select>
      <div>您选中了:{{selOption}}</div>
    </div>
    <script>
      const app = Vue.createApp({
        data() {
          return {
            selOption: 'Baidu',
            sites: [
              { id: 1, name: 'Google' },
              { id: 2, name: 'Yandex' },
              { id: 3, name: 'Firefox' },
              { id: 4, name: 'Baidu' },
            ],
          }
        },
        methods: {
          changeVal: function (event) {
            ;(this.selOption = event.target.value),
              alert('您选中了' + this.selOption)
          },
        },
      })
      app.mount('#app')
    </script>
  </body>
</html>

image

posted @ 2022-04-27 15:26  wjxuriel  阅读(113)  评论(0)    收藏  举报