Empty ref(”) variable after assigning .value to this variable in composition API vue 3.

huangapple go评论60阅读模式
英文:

Empty ref('') variable after assigning .value to this variable in composition API vue 3

问题

我在将字符串分配给ref<string>('')之后,使用ref属性进行请求时,请求中的.value为空。当我在onMounted()方法内调用该方法时,为什么会出现这种情况?但是,在请求之前,当我在控制台中打印变量时,它显示了预期的值。我分享了代码

<script setup lang="ts">
import { onMounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import CustomTable from './CustomTable.vue'

const router = useRouter()
let today: Date
let fechaColaEmails = ref('')

// HTTP请求URL
const url = `${import.meta.env.VITE_APP_ROOT_API}${import.meta.env.VITE_BACKEND_DASHBOARD_DESA}/emails?fecha=${fechaColaEmails.value}`

async function pedirEmails() {
  try {
    console.log('dentro del metodo pedir emails: ' + url)
    const { data } = await axios.get<any[]>(url)
    emails.value = data
  } catch (error) {
    console.log(error)
  }
}

async function submitFecha(fecha: any) {
  let fechT: string = fecha.target.value
  let arrayFecha = fechT.split('-')
  fechaColaEmails.value = arrayFecha[2] + '/' + arrayFecha[1] + '/' + arrayFecha[0]
  console.log('hola')
}

onMounted(async () => {
  today = new Date()
  let dd = String(today.getDate())
  let mm = String(today.getMonth() + 1) // January is 0!
  let yyyy = today.getFullYear()
  fechaColaEmails.value = dd + '/' + mm + '/' + yyyy
  console.log('onMounted: ', fechaColaEmails.value)
  console.log('esta es la peticion en onmounted: ' + url)
  await pedirEmails()
  console.log('esta es la peticion despues de pedirla: ' + url)
})

function ruta(event: number): void {
  router.push({ name: 'detallesemail', params: { contador: event } })
}
let emails = ref([
  { }
])
</script>

希望这可以帮助你解决问题。

英文:

I'm making a request with a ref property, after I assign a string to a ref<string>('') the .value it is empty in the request when I'm calling the method inside the onMounted(), why is that possible? but when I print in console before the request the variable it shows the expected value. I share the code

&lt;script setup lang=&quot;ts&quot;&gt;
import { onMounted, ref, watch } from &#39;vue&#39;
import { useRouter } from &#39;vue-router&#39;
import axios from &#39;axios&#39;
import CustomTable from &#39;./CustomTable.vue&#39;
const router = useRouter()
let today: Date
let fechaColaEmails = ref(&#39;&#39;)
//llamada http
const url = `${import.meta.env.VITE_APP_ROOT_API}${
import.meta.env.VITE_BACKEND_DASHBOARD_DESA
}/emails?fecha=${fechaColaEmails.value}`
async function pedirEmails() {
try {
console.log(&#39;dentro del metodo pedir emails: &#39; + url)
const { data } = await axios.get&lt;any[]&gt;(url)
emails.value = data
} catch (error) {
console.log(error)
}
}
async function submitFecha(fecha: any) {
let fechT: string = fecha.target.value
let arrayFecha = fechT.split(&#39;-&#39;)
fechaColaEmails.value = arrayFecha[2] + &#39;/&#39; + arrayFecha[1] + &#39;/&#39; + arrayFecha[0]
console.log(&#39;hola&#39;)
}
onMounted(async () =&gt; {
today = new Date()
let dd = String(today.getDate())
let mm = String(today.getMonth() + 1) //January is 0!
let yyyy = today.getFullYear()
fechaColaEmails.value = dd + &#39;/&#39; + mm + &#39;/&#39; + yyyy
console.log(&#39;onMounted: &#39;, fechaColaEmails.value)
console.log(&#39;esta es la peticion en onmounted: &#39; + url)
await pedirEmails()
console.log(&#39;esta es la peticion despues de pedirla: &#39; + url)
})
function ruta(event: number): void {
router.push({ name: &#39;detallesemail&#39;, params: { contador: event } })
}
let emails = ref([
{  }
])
&lt;/script&gt;

答案1

得分: 3

看起来你假设url是一个计算属性,在更改fechaColaEmails时会发生变化。但它只是一个字符串:

let fechaColaEmails = ref('')

const url = `${import.meta.env.VITE_APP_ROOT_API}${
  import.meta.env.VITE_BACKEND_DASHBOARD_DESA
}/emails?fecha=${fechaColaEmails.value}` // <---- fechaColaEmails.value会立即解析为''

如果你想使它具有响应性,你需要将它放入一个真正的计算属性:

const url = computed(() => `...fecha=${fechaColaEmails.value}`)

现在,url在每次fechaColaEmails更改时都会重新计算。


你可能需要检查,仅在实际需要时构建url是否足够,如果不需要对它们做出响应,那么使值具有响应性是没有意义的:

async function pedirEmails() {
  const url = `...`
  try {
    const { data } = await axios.get<any[]>(url)
    ...
}
英文:

It looks like you assume url is a computed property, that changes when you change fechaColaEmails. But it is just a string:

let fechaColaEmails = ref(&#39;&#39;)
const url = `${import.meta.env.VITE_APP_ROOT_API}${
import.meta.env.VITE_BACKEND_DASHBOARD_DESA
}/emails?fecha=${fechaColaEmails.value}` // &lt;---- fechaColaEmails.value will be resolved immediatelly to &#39;&#39;

If you want to make it responsive, you need to put it into an actual computed property:

const url = computed(() =&gt; `...fecha=${fechaColaEmails.value}`)

Now url is recomputed everytime fechaColaEmails change.


You might want to check if it is enough to build the url only when you actually need it, there is no point in making values reactive if you don't need to react to them:

async function pedirEmails() {
const url = `...`
try {
const { data } = await axios.get&lt;any[]&gt;(url)
...
}

huangapple
  • 本文由 发表于 2023年7月17日 18:33:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/76703609.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定