简体   繁体   English

Vue日期选择器并提交所选日期

[英]Vue datepicker and submitting selected date

I'm using the vue-date-picker package in my laravel application, and upon selecting a date from the datepicker I can see in my vue developer tools pickedValue with the selected date. 我在laravel应用程序中使用了vue-date-picker picker程序包,并且从datepicker中选择了一个日期后,便可以在vue开发人员工具中pickedValue带有选定日期的pickedValue Currently my code is plain: 目前我的代码很简单:

<datepicker></datepicker>

But I'm wondering, is the pickedValue the correct syntax to use for submitting this in a form? 但是我想知道, pickedValue是否是用于以表格形式提交的正确语法? Do I need an onChange event, or can I just use datepicker.pickedValue or something similar? 我需要一个onChange事件,还是可以只使用datepicker.pickedValue或类似的东西? I just want to set the picked date to a variable for an axios post. 我只想将选择的日期设置为axios帖子的变量。

UPDATE: 更新:

<div v-cloak v-if="isScheduledTask">
  <datepicker v-model="pickedValue" name="pickedValue" id="pickedValue" ></datepicker>
</div>

data() {
  return{
    pickedValue:'',
  }
}

You should use you local data property and pass it as a :value prop. 您应该使用本地数据属性,并将其作为:value属性传递。 Getting inner state of component through this.$refs.datepicker.pickedValue is considered a bad practice. 通过this.$refs.datepicker.pickedValue获取组件的内部状态被认为是不好的做法。 It's considered standard de-facto to use props and events to communicate between parent and child components in Vue.js. 使用道具和事件在Vue.js中的父组件和子组件之间进行通信被认为是事实上的标准。 There are some drawbacks of using your approach: 使用您的方法有一些缺点:

  1. You can't set the value of the datepicker outside. 您无法在外部设置datepicker的值。

  2. Another developer would be confused with such approach. 另一位开发人员将对这种方法感到困惑。

  3. You are breaking one way data flow approach. 您正在打破一种数据流方法。

  4. Your code is prone to bug, because that's local component variables. 您的代码容易出错,因为那是局部组件变量。 Every time name of this property can change. 该属性的名称每次都可以更改。

Alert from Vue.js docs: 来自Vue.js文档的警报:

Use $parent and $children sparingly - they mostly serve as an escape-hatch. 谨慎使用$parent$children它们主要用作逃生舱口盖。 Prefer using props and events for parent-child communication. 首选使用道具和事件进行亲子沟通。

Update 更新

DO NOT EVER DO IT AGAIN 永远不要再做

In your case you have no other options, but to access it through refs . 在您的情况下,您没有其他选择,只能通过refs进行访问。

this.$refs.datepicker.pickedValue
<div>
  <datepicker ref="datepicker" value="2018-9-5"></datepicker>
</div>

...
methods: {
  sendForm() {
    console.log(`Picked date ${this.$refs.datepicker.pickedValue}`)
  }
}
...

Update 更新

It's very bad pattern, but you have no choice working with library that does not emit ANY events. 这是非常糟糕的模式,但是您别无选择地使用不会发出任何事件的库。

DON'T DO IT EVER AGAIN!!! 永远不要这样做!!!

<datepicker ref="datepicker" @click.native="method"></datepicker>
data() {
  return {
    value: ''
  }
},
methods: {
  method() {
    this.value = this.$refs.datepicker.pickedValue
  },
},

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM