vue中下拉框的双向数据绑定select option

558 阅读1分钟

// 用v-for for of 遍历数组得到数据,v-model进行双向数据绑定

// v-bind,生成动态属性,不然不加冒号直接写value="item.value",会当成字符串解析

<!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({
      // 变量
      data() {
        return {
          selectValue: "",
          ajaxValue: [
            { text: "北京", value: "beijing" },
            { text: "上海", value: "shanghai" },
            { text: "广州", value: "guangzhou" },
            { text: "深圳", value: "shenzhen" },
          ],
        };
      },
      // 模板
    //   用v-for for of 遍历数组得到数据,v-model进行双向数据绑定
    // v-bind,生成动态属性,不然不加冒号直接写value="item.value",会当成字符串解析
      template: `
        <h1>城市{{selectValue}}</h1>
        <select v-model="selectValue">
            <option disabled>请选择你的城市</option>
            <option v-for="item of ajaxValue"  :value="item.value">{{item.text}}</option>
            </select>
        `,
    });
    const vm = app.mount("#root");
  </script>
</html>