vue 子组件改变父组件的值

项目中遇到,子组件改变选值时,想改变父组件的值,尝试了两种办法,用到的watchcomputed方式,看个人喜爱

第一种:

父组件传入一个方法,子组件的值改变时,调用父组件的方法改变父组件的值

父组件

<level-select :level="form.level" @change="changeValue" />

<script>
import LevelSelect from '@/components/LevelSelect'

export default {
  components: { LevelSelect },
  data() {
    return {
      form: {
        level: 1
      }
    }
  },
  methods: {
    changeValue(val) {
      this.form.level = val
    }
  }
}
</script>

子组件

<template>
  <div>
    <label style="display: inherit;">权限</label>
    <el-select v-model="levelSelected" placeholder="请选择" style="width:100%" size="medium">
      <el-option
        v-for="item in levels"
        :key="item.level"
        :label="item.name"
        :value="item.level"
      />
    </el-select>
  </div>
</template>

<script>
export default {
  props: { 
    level: { 
      type: Number,
      default: 0 
    }
  },
  data() {
    return {
      levels: [
        { name: '公开', level: 0 },
        { name: '会员可见', level: 1 },
        { name: '需要密码', level: 2 },
      ]
    }
  },
  computed: {
    levelSelected: {
      get() {
        return this.level
      },
      set(val) {
        this.$emit('change', val)
      }
    }
  } 
</script>

<style>

</style>

第二种:

需要用到 .sync,因为想父组件里面简洁一点,所以我选用的是这一种方式。实例如下:

父组件

<level-select :level.sync="form.level" />

<script>
import LevelSelect from '@/components/LevelSelect'

export default {
  components: { LevelSelect },
  data() {
    return {
      form: {
        level: 1
      }
    }
  }
}
</script>

子组件

<template>
  <div>
    <label style="display: inherit;">权限</label>
    <el-select v-model="levelSelected" placeholder="请选择" style="width:100%" size="medium">
      <el-option
        v-for="item in levels"
        :key="item.level"
        :label="item.name"
        :value="item.level"
      />
    </el-select>
  </div>
</template>

<script>
export default {
  props: { 
    level: { 
      type: Number,
      default: 0 
    }
  },
  data() {
    return {
      levels: [
        { name: '公开', level: 0 },
        { name: '会员可见', level: 1 },
        { name: '需要密码', level: 2 },
      ],
      levelSelected: this.level
    }
  },
  watch: {
    levelSelected(newVal) {
      this.$emit('update:level', newVal);
    }
  }
} 
</script>

<style>

</style>

子组件的权限值改变时,父组件的level也会相应的改变