<el-form :model="listParam" label-position="left" inline>
    <el-form-item prop="searchKey">
       <el-input v-model="listParam.searchKey" placeholder="请输入关键字" clearable size="small"></el-input>
    </el-form-item>
    <el-form-item prop="mainFollower">
      <el-input v-model="listParam.mainFollower" placeholder="请输入跟进人姓名" clearable size="small"></el-input>
    </el-form-item>
</el-form>
1.watch监听单一的数据:
setup() {
    const state = reactive({
        listParam: {
          searchKey: ""
        }
    })
    watch(() => state.listParam.searchKey, (newVal,oldVal) => {
        console.log(newVal, oldVal)
        state.listParam.searchKey = newVal.trim()
    })
    return {
        ...toRefs(state)
    }
}
2.watch监听多个数据,watch也可以变为非惰性的 立即执行的 添加第三个参数 immediate: true
setup() {
    const state = reactive({
        listParam: {
          searchKey: "",
          mainFollower: ""
        }
    })
    watch([() => state.listParam.customerName, () => state.listParam.mainFollower],
      ([newCustomerName, newMainFoller],[oldCustomerName,oldMainFoller]) => {
        state.listParam.customerName = newCustomerName.trim()
        state.listParam.mainFollower = newMainFoller.trim()
    },{
       immediate: true
    })
    return {
        ...toRefs(state)
    }
}
3.使用watchEffect监听数据,可以单个或多个,不需要传入监听的数据源,而是直接执行里面的方法,获取到更新后的值。
setup() {
    const state = reactive({
        listParam: {
          searchKey: "",
          mainFollower: ""
        }
    })
    watchEffect(() => {
      state.listParam.searchKey = state.listParam.searchKey ? state.listParam.searchKey.trim() : ""
      state.listParam.mainFollower= state.listParam.mainFollower? state.listParam.mainFollower.trim() : ""
    })
    return {
        ...toRefs(state)
    }
}
总结:
- watchEffect 不需要指定监听的属性,他会自动的收集依赖,只要在回调函数中引用到了响应式的属性,那么当这些属性变动的时候,这个回调都会执行,而 watch 只能监听指定的属性而作出变动(v3开始能够同时指定多个)。
- watch 能够获取到新值与旧值(更新前的值),而 watchEffect 是拿不到的。
- watchEffect 在组件初始化的时候就会执行一次用以收集依赖,收集到的依赖发生变化时再执行。而 watch 则是直接指定依赖项。