Vuexを使用したNativescriptVue Timepicker
Aug 21 2020
私は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', newValue)
}
},
},
次に、私の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: {
}
});
ストアのデフォルト値がコンポーネントに正常に取り込まれているように見えますが、ピッカーで時間を変更すると、計算された関数の「set」部分が起動せず、console.logsが起動することもありません。
別の変更イベントを聞く必要がありますか?ここのドキュメントでは、これについては詳しく説明していません。
助けてくれてありがとう!
回答
5 Phil Aug 25 2020 at 10:27
Vueのすべての小道具は一方向にバインドされているため、Timepicker
小道具は初期値の設定にのみ使用されます。
代わりに、ストアからの読み取り/ストアへの書き込みをv-model
行う計算されたゲッターおよびセッターとのバインディングを使用できます
<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
<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())
}
}
}