vue.js - 如何在 vuejs3 应用程序的设置中调用方法?
问题描述
在 vuejs3 应用程序中,我使用 axios 方法从 db 检索数据,例如:
<script>
import appMixin from '@/appMixin'
import app from './../../App.vue' // eslint-disable-line
import axios from 'axios'
const emitter = mitt()
export default {
name: 'adminCategoriesList',
mixins: [appMixin],
data: function () {
return {
categoriesPerPage: 20,
currentPage: 1,
categoriesTotalCount: 0,
categories: []
}
},
components: {
},
setup () {
const adminCategoriesListInit = async () => {
this.loadCategories() // ERROR HERE
}
function onSubmit (credentials) {
alert(JSON.stringify(credentials, null, 2))
console.log('this::')
console.log(this)
console.log('app::')
}
onMounted(adminCategoriesListInit)
return {
// schema,
onSubmit
}
}, // setup
methods: {
loadCategories() {
...
}
我在浏览器的控制台中遇到错误:
Cannot read property 'loadCategories' of undefined
如果要删除“这个”。在 loadCategories 调用中出现错误:
'loadCategories' is not defined
我需要将 loadCategories 作为方法,因为我需要从不同的地方调用它。
哪种方式是正确的?
谢谢!
解决方案
您可以在同一个组件中使用组合和选项 api,但对于不同的属性和方法,在您的情况下,可以使用或在setup
钩子中定义数据属性,这些方法可以定义为普通的 js 函数:ref
reactive
import {ref} from 'vue'
export default {
name: 'adminCategoriesList',
mixins: [appMixin],
components: {
},
setup () {
const categoriesPerPage= ref(20);
const currentPage=ref(1);
const categoriesTotalCount=ref(0),
const categories=ref[])
const adminCategoriesListInit = async () => {
loadCategories()
}
function onSubmit (credentials) {
alert(JSON.stringify(credentials, null, 2))
}
functions loadCategories(){
...
}
onMounted(adminCategoriesListInit)
return {
// schema,
onSubmit,
categoriesPerPage,
currentPage,
categoriesTotalCount,
categories
}
},
定义的属性ref
可以property.value
在模板中使用/变异和使用,例如{{property}}
推荐阅读
- python - 加快学校项目数据文件读取程序
- javascript - 如何在 jQuery 和 html 中计算文本框的值
- sql-server - XPath/XQuery - 将具有命名空间属性的字段作为值/查询获取?
- java - Android Studio 初学者;
- python - 熊猫如何用 int64 空标记 -999999 替换
没有铸造浮动? - python - 将 mongodb 集合名称作为变量不起作用
- php - 如何防止在 Symfony 中延迟加载易受攻击的实体
- sql - 如何限制oracle表的记录有限
- google-app-engine - 部署 gcloud 应用引擎时的权限
- docker - 在 Dockerfile 中恢复 SQL Server DB.bak