问题遇到的现象和发生背景
在FInd.vue中vue导入axios错误
问题相关代码,请勿粘贴截图
<script >
import axios from 'axios';
import { onMounted } from 'vue'
export default {
data () {
onMounted(() => {
axios.get('http://localhost:3000/banner?type=2').then((res) => {
console.log(res);
})
})
return {
value: "",
images: [
'https://img.yzcdn.cn/1.jpg',
'https://img.yzcdn.cn/2.jpg'
]
}
}
}
</script>
运行结果及报错内容
vue.runtime.esm.js?c320:1897
TypeError: (0 vue__WEBPACK_IMPORTED_MODULE_1__.onMounted) is not a function
at VueComponent.data (Find.vue?6e72:34:1)
at getData (vue.runtime.esm.js?c320:4761:1)
at initData (vue.runtime.esm.js?c320:4717:1)
at initState (vue.runtime.esm.js?c320:4655:1)
at VueComponent.Vue._init (vue.runtime.esm.js?c320:5020:1)
at new VueComponent (vue.runtime.esm.js?c320:5168:1)
at createComponentInstanceForVnode (vue.runtime.esm.js?c320:3304:1)
at init (vue.runtime.esm.js?c320:3133:1)
at merged (vue.runtime.esm.js?c320:3322:1)
at createComponent (vue.runtime.esm.js?c320:6022:1)
vue.runtime.esm.js?c320:619
[Vue warn]: Error in data(): "TypeError: (0 , vue__WEBPACK_IMPORTED_MODULE_1__.onMounted) is not a function"
found in
---> <Anonymous>
<App> at src/App.vue
<Root>
我的解答思路和尝试过的
我想要达到的结果
onMounted改成mounted
script标签添加setup 语法糖
<script setup>
因为vue3 现在没有this 以及原型的概念,你要么使用 globalProperties 去进行挂载
要么使用 provide inject去进行全局获取
改成这样就不会报错了
<script >
import { onMounted } from "vue";
import axios from 'axios';
export default {
setup () {
const images = [
'https://img.yzcdn.cn/1.jpg',
'https://img.yzcdn.cn/2.jpg'
];
onMounted(() => {
axios.get('http://localhost:3000//banner?type=2').then((res) => {
console.log(res);
})
})
return {
images,
};
},
};
</script>
但是又冒出两个警告
[Vue warn]: Property or method "images" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.
found in
---> <Find> at src/views/Find.vue
<App> at src/App.vue
<Root>
[Vue warn]: Property or method "value" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.
found in
---> <Find> at src/views/Find.vue
<App> at src/App.vue
<Root>
我发现在这里
<van-search
placeholder="请输入搜索关键词"
shape="round"
v-model="value"
class="search"
/>
<van-swipe :autoplay="3000" indicator-color="white">
<van-swipe-item v-for="(image, index) in images" :key="index">
<img v-lazy="image" />
</van-swipe-item>
</van-swipe>
调用该模块,但我在script的return输入value,imges并没有解决问题