vue 为什么需要用watch监听props才会更新视图

slowly
  • 21

题目描述

关于vue props的更新问题,我有需要关联两个select组件,前者用来筛选公司,后者用来筛选公司中的部门,所以当公司slecet清空时,后者slecet也自动清空,当时当我在父组件的公司select组件的change事件中,将部门的v-model变量置空时,视图并未更新

题目来源及自己的思路

相关代码

父组件

async handleCompany(value) {
      this.listQuery.com_id = value
      this.listQuery.dept_id = ''
      const { items } = await fetchDept({ com_id: value })
      this.deptOptions = items
      if (value === '') {
        this.deptOptions = []
      }
      this.listQuery.page = 1
      this.getList()
    },
      <BaseSelect v-if="userRole===1" v-model="listQuery.com_id" :options="companyOptions" placeholder="所有公司" style="width:105px" @clear="clearHandle" @handlechange="handleCompany" />
      <BaseSelect v-if="[11,1].includes(userRole)" v-model="listQuery.dept_id" :options="deptOptions" placeholder="所有部门" style="width:105px" @handlechange="handleFilter" />

#### 子组件

<template>
  <div style="display:inline-block">
    <el-select
      v-model="selectValue"
      :placeholder="placeholder"
      size="mini"
      :clearable="clearable"
      :filterable="filterable"
      @clear="clearHandle"
      @change="handleChange"
    >
      <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id" />
    </el-select>
  </div>
</template>

<script>
export default {
  name: 'BaseSelect',
  props: {
    value: {
      type: String,
      default: function() {
        return ''
      }
    },
    disabled: {
      type: Boolean,
      default: false
    },
    clearable: {
      type: Boolean,
      default: true
    },
    filterable: {
      type: Boolean,
      default: false
    },
    placeholder: {
      type: String,
      default: function() {
        return ''
      }
    },
    options: {
      type: Array,
      default: function() {
        return []
      }
    }
  },
  data() {
    return {
      selectValue: this.value,
      selectOptions: this.options
    }
  },
  // 当公司筛选清空时,将部门条件置空未生效
  watch: {
    value() {
      this.selectValue = this.value
    },
    options() {
      this.selectOptions = this.options
    }
  },
  methods: {
    handleChange(val) {
      this.$emit('handlechange', val)
    },
    clearHandle() {
      this.$emit('clear')
    }
  }
}
</script>

只有我用watch监听的时候才更新视图

回复
阅读 684
3 个回答
✓ 已被采纳

因为你子组件内赋值给selectOptions变量了,虽然你改变了option但是还是存在selectOptions,所以只有你再次赋值后才会清空

试试看

this.$set(this,'deptOptions',[])

`async handleCompany(value) {

  this.listQuery.com_id = value
  // this.listQuery.dept_id = ''
  this.$set(this, 'listQuery.dept_id', '')
  const { items } = await fetchDept({ com_id: value })
  this.deptOptions = items
  if (value === '') {
    // this.deptOptions = []
    this.$set(this, 'deptOptions', [])
  }
  this.listQuery.page = 1
  this.getList()
},`

我取消掉watch使用$set没有成功
你知道吗?

宣传栏