Vue JS:无法从创建的功能中更新dom

时间:2019-11-28 07:09:52

标签: vue.js vue-component

我通过

创建了我的项目
vue init webpack project
@vue/cli 4.0.5

这是我的App.vue。

<template>
  <div id="app">
      <router-view/>
  </div>
</template>

<script>

export default {
  name: 'App'
}
</script>

路由器文件

let router = new Router({
  routes: [
    {
      path: '/videos',
      name: 'Videos',
      component: Videos
    }
  ]
})

“视频”文件夹下的文件

index.js

import Videos from './Videos'
export default Videos

Videos.vue

<template>
  <div>
    <ul>
     <li v-for="video in videos" :key="video.index">
      {{ video.index }} - {{ video.value }}
     </li>
    </ul>
    <div class="button">
      <cv-button @click="submit">Submit</cv-button>
    </div>
  </div>
</template>
<script>
import axios from 'axios'
export default {
  created: () => {
    const _this = this
    const url = process.env.API_URL
    axios.get(url + 'api/hello', {mode: 'no-cors'})
      .then(response => {
        const resource = response.data
        const videos = resource.videos
        _this.videos = Object.keys(videos).map((key) => {
          return {
            index: key,
            value: videos[key]
          }
        })
      })
  },
  data: () => {
    return {
      videos: []
    }
  },
  methods: {
    submit: function () {
      const url = process.env.API_URL
      axios.get(url + 'api/videos')
        .then(response => {
          console.log(response)
          const resource = response.data
          const videos = resource.videos
          this.videos = Object.keys(videos).map((key) => {
            return {
              index: key,
              value: videos[key]
            }
          })
        })
    }
  }
}
</script>

基本上,我想在created函数中获取视频列表,但是this.videos_this.videos都不起作用。当我尝试在this函数中登录created时,我看到的是{} JSON对象,而不是VueComponent。

{
  a: {computed: {}, data: f, ...},
  videos: [{...},{...}]
}

当我尝试通过单击按钮来触发触发submit函数的列表时,它按预期工作,并且this是VueComponent。

VueComponent {_uid: 23, _isVue: true, $options: {…}, _renderProxy: Proxy, _self: VueComponent, …}

我不明白这里发生了什么?为什么我使用submit函数而不在created函数内部工作? 谢谢

1 个答案:

答案 0 :(得分:0)

使用created: () => {}表示法创建的函数在全局范围内执行。尝试created() {}