我通过
创建了我的项目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
函数内部工作?
谢谢
答案 0 :(得分:0)
使用created: () => {}
表示法创建的函数在全局范围内执行。尝试created() {}