computed 和 watch 联用
情景:有一个变量的改变时,会调用多个组件的多个接口
例如大屏的这个下拉框按钮,选择日期的时候,整个大屏的数据都需要更新
- 先在 store 文件夹下的 index.js 文件声明一个变量,全局使用
import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'
import app from './modules/app'
import settings from './modules/settings'
import user from './modules/user'
Vue.use(Vuex)
const store = new Vuex.Store({
modules: {
app,
settings,
user
},
state: {
updateDataNum: 0,
area: '石家庄',
adcode: '0311',
year: '',
month: '',
unfinished: {},
closed: {},
token: '',
computedVal: "1" // 这是声明的变量
},
getters
})
export default store
- 给下拉框绑定值
<el-select
v-model="computedVal"
placeholder="请选择"
@change="selChange()"
>
<el-option
v-for="item in options"
:key="item.value"
:label="item.label"
:value="item.value"
>
</el-option>
</el-select>
- 声明计算属性并监听,在数据发生改变的时候,调用查询数据的接口
computed: {
computedVal: {
get () {
return this.$store.state.computedVal
},
set (newValue) {
this.$store.state.computedVal = newValue
return newValue
}
}
},
watch: {
computedVal (newVal, oldVal) {
console.log('🚀 ~ file: index.vue:60 ~ computedVal ~ oldVal:', oldVal)
console.log('🚀 ~ file: index.vue:60 ~ computedVal ~ newVal:', newVal)
this.getData()
}
},
这样在下拉框选中的数据发生改变的时候,就会自动调用查询数据的接口