You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将methods返回值传入mounted钩子中使用?

解决方法

核心是把拆分后的word和num存到Vue的响应式数据中,这样组件的各个钩子和方法都能访问到:

  1. 在组件的data中声明word和num两个空数组:
data() {
  return {
    mixed: [['John',34],['Mary',4],['Jack',234]],
    word: [],
    num: []
  }
}
  1. 在methods里编写拆分方法,将结果赋值给响应式数据:
methods: {
  splitMixedList() {
    // 遍历嵌套列表拆分
    this.mixed.forEach(item => {
      this.word.push(item[0])
      this.num.push(item[1])
    })
    // 也可以用解构写法更简洁:
    // const { word, num } = this.mixed.reduce((acc, [w, n]) => {
    //   acc.word.push(w)
    //   acc.num.push(n)
    //   return acc
    // }, { word: [], num: [] })
    // this.word = word
    // this.num = num
  }
}
  1. 在mounted钩子中调用拆分方法,之后就能直接使用this.word和this.num:
mounted() {
  this.splitMixedList()
  console.log('拆分后的名字列表:', this.word)
  console.log('拆分后的数字列表:', this.num)
}

这样处理后,word和num作为组件的响应式数据,不仅在mounted里能访问,其他钩子或模板中也能直接使用。

内容的提问来源于stack exchange,提问作者Blank Xxx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 22:57:04