两周掌握Vue3:自定义指令、路由、ajax
warning:
这篇文章距离上次修改已过204天,其中的内容可能已经有所变动。
在Vue3中,我们可以通过以下方式创建自定义指令、使用Vue Router以及进行Ajax请求:
- 自定义指令:
// 注册一个全局自定义指令 `v-focus`,该指令用于输入框自动获取焦点
const app = Vue.createApp({...});
app.directive('focus', {
// 当被绑定的元素挂载到 DOM 上时调用
mounted(el) {
el.focus(); // 元素获取焦点
}
});
- 使用Vue Router:
import { createRouter, createWebHistory } from 'vue-router';
// 定义路由
const routes = [
{ path: '/', component: Home },
{ path: '/about', component: About }
];
// 创建 router 实例
const router = createRouter({
history: createWebHistory(),
routes
});
const app = Vue.createApp({...});
app.use(router);
- Ajax请求:
// 使用 fetch API 进行 Ajax 请求
const app = Vue.createApp({
data() {
return {
message: null
};
},
mounted() {
this.fetchData();
},
methods: {
fetchData() {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
this.message = data.message;
})
.catch(error => {
console.error('Error fetching data: ', error);
});
}
}
});
以上代码展示了如何在Vue3应用中注册自定义指令、使用Vue Router配置路由以及如何通过fetch API发送Ajax请求。
评论已关闭