Vue

Vue 中 Select Option value 不能是对象

2017-07-20  本文已影响0人  建博姓李

vue中使用select时 如果使用 v-model 那么 option 值不能使用对象,需要将对象转换成字符串

<template>
  <div>
    <select class="form-select" name="" v-model="currentValue" @change="onChange">
      <option :value="data | object2String" v-for="data in dataList">{{data.name}}</option>
    </select>
  </div>
</template>
<script>
const heros = [
  { name: '刘炫德', nickName: '刘备', value: '10001' },
  { name: '张翼德', nickName: '张飞', value: '10002' },
  { name: '关云长', nickName: '关羽', value: '10003' },
  { name: '赵子龙', nickName: '赵云', value: '10004' }
]
// string 转 object
const string2Object = str => {
  return JSON.parse(obj)
}
// object 转 string
const object2String = obj => {
  return JSON.stringify(str)
}

export default {
  props: {
    value: {
      type: Object,
      default () {
        return { name: '关云长', nickName: '关羽', value: '10003' }
      }
    }
  },
  filters: {
    string2Object,
    object2String
  }
  data: () => ({
    dataList: heros,
    currentValue: string2Object(this.value)
  }),
  methods: {
    onChange () {
      this.$emit('input', object2String(this.currentValue)) // 将currentValue 转成 object
    }
  }
}
</script>

定义一个 filter object2string

绑定 option value 的时候使用 object2string 将 对象转换成字符串

返回当前选中值的时候使用 JSON.pares() 将字符串转成Object

上一篇下一篇

猜你喜欢

热点阅读