如何将methods返回值传入mounted钩子中使用?
解决方法
核心是把拆分后的word和num存到Vue的响应式数据中,这样组件的各个钩子和方法都能访问到:
- 在组件的
data中声明word和num两个空数组:
data() { return { mixed: [['John',34],['Mary',4],['Jack',234]], word: [], num: [] } }
- 在
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 } }
- 在
mounted钩子中调用拆分方法,之后就能直接使用this.word和this.num:
mounted() { this.splitMixedList() console.log('拆分后的名字列表:', this.word) console.log('拆分后的数字列表:', this.num) }
这样处理后,word和num作为组件的响应式数据,不仅在mounted里能访问,其他钩子或模板中也能直接使用。
内容的提问来源于stack exchange,提问作者Blank Xxx
相关产品推荐
相关产品推荐

