问题描述
我正在使用Nativescript-Vue应用程序,并且试图使用Vuex存储来自Timepicker的小时和分钟,以用于其他页面。我已经尝试使用计算属性来捕获事件,但是有没有更好的方法可以通过Vue做到这一点?
这就是我所拥有的:
// In NotifyTimePicker.vue (a custom Time-picking modal)
// Template:
<TimePicker row="2" col="0" colSpan="3" horizontalAlignment="center" :hour="selectedFromHour" :minute="selectedFromMinute" />
//Script
computed: {
selectedFromHour: {
get: function () {
return this.$store.state.notifyFromTimeHour
},set: function (newValue) {
console.log(`Attempting to Update Store with new From Hour = ${newValue}`)
this.$store.commit('changeNotifyFromTimeHour',newValue)
}
},selectedFromMinute: {
get: function () {
return this.$store.state.notifyFromTimeMinute
},set: function (newValue) {
console.log(`Attempting to Update Store with new From Minute = ${newValue}`)
this.$store.commit('changeNotifyFromTimeMinute',},
然后,在我的Vuex商店中:
export default new Vuex.Store({
state: {
notifyFromTimeHour: 9,notifyFromTimeMinute: 30,mutations: {
changeNotifyFromTimeHour (state,hour) {
state.notifyFromTimeHour = hour
},changeNotifyFromTimeMinute (state,minute) {
state.notifyFromTimeMinute = minute
},actions: {
}
});
看来,将Store中的默认值很好地拉入了组件中,但是在选择器中更改时间时,计算功能的``设置''部分永远不会触发,并且我也从未看到控制台触发
我应该听其他的变更事件吗?文档here对此没有太多详细说明。
感谢您的帮助!
解决方法
由于Vue中的所有道具都是单向绑定,因此Timepicker
道具仅用于设置初始值。
相反,您可以将v-model
绑定与计算的 getter 和 setter 结合使用,该绑定可读取/写入商店
<TimePicker
row="2"
col="0"
colSpan="3"
horizontalAlignment="center"
v-model="selectedTime"
/>
export default {
computed: {
selectedTime: {
get () {
const time = new Date()
time.setHours(
this.$store.state.notifyFromTimeHour,this.$store.state.notifyFromTimeMinute)
return time
},set (time) {
this.$store.commit('changeNotifyFromTimeHour',time.getHours())
this.$store.commit('changeNotifyFromTimeMinute',time.getMinutes())
}
}
}
}
或者,要收听更新,您需要使用timeChange
event
<TimePicker
row="2"
col="0"
colSpan="3"
horizontalAlignment="center"
:hour="selectedFromHour"
:minute="selectedFromMinute"
@timeChange="changeTime"
/>
import { mapState } from "vuex"
export default {
computed: mapState({
selectedFromHour: "notifyFromTimeHour",selectedFromMinute: "notifyFromTimeMinute"
}),methods: {
changeTime (payload) {
// documentation doesn't say what the event payload is,let's assume it's a Date
this.$store.commit('changeNotifyFromTimeHour',payload.getHours())
this.$store.commit('changeNotifyFromTimeMinute',payload.getMinutes())
}
}
}