前端菜戌鲲 2021-04-22 17:59 采纳率: 100%
浏览 154
已采纳

为什么我这个函数在created钩子里调用是正常的,在mounted钩子里就不行?

<template>
  <div>
    <div class="block">
      <span class="demonstration">默认 click 触发子菜单</span>
      <el-cascader
        v-model="value"
        :options="newOptions"
        @change="handleChange"
      />
    </div>

  </div>
</template>

<script>
import mixin from './mixin'
export default {
  name: 'Home',
  mixins: [mixin],
  data() {
    return {
      value: [],
      newOptions: []
    }
  },
  mounted() {
    this.filterOptions1(this.newOptions, this.options)
  },
  created() {
    // this.filterOptions1(this.newOptions, this.options)
  },
  methods: {
    handleChange() {
      console.log('改变了')
    },
    filterOptions() {
      const str = JSON.stringify(this.options)
      console.log(str)
      let str1 = str.replace(/(city|area)/g, (s) => {
        return 'children'
      })
      str1 = str.replace(/name/g, (s) => {
        return 'label'
      })
      console.log(str1)
    },
    // 想要的结构  [{label:'',value:'',children:[]}]
    // 结构 [{name:'',city:[{name:'',area:['','','']}]}]
    filterOptions1(newObj, obj) {
      for (const key in obj) {
        const label = obj[key]['name']
        const citys = obj[key]['city']
        const newCitys = []
        for (const city in citys) {
          const cityLabel = citys[city]['name']
          const areas = citys[city]['area']
          const newAreas = []
          areas.forEach((item, index) => {
            const newArea = { label: item, value: item }
            newAreas.push(newArea)
          })
          const c = { label: cityLabel, value: cityLabel, children: newAreas }
          newCitys.push(c)
        }
        newObj[key] = { label, value: label, children: newCitys }
      }
    }
  }
}
</script>

<style>

</style>
  • 写回答

7条回答 默认 最新

  • 卷腹肌肉侠 2021-04-23 15:06
    关注

    首先,你的options是一个数组,我们知道,对于数组想要实现数据双向绑定直接更改里面的内容是不行的。所以你那个filterOptions1方法本质上是错误的。

    至于为什么在created里有用,而mounted没用,是因为在created里就给数据赋值了,这个赋值是在页面渲染之前,所以你会看到页面渲染成功,但是其实这是个假象,因为这个并不是双向绑定的。你如果用你的filterOptions1方法再给里面的数据做改动处理,你会发现里面的数据还是你created时候的数据。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(6条)

报告相同问题?

悬赏问题

  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan