本文共 2546 字,大约阅读时间需要 8 分钟。
在开始开发前需要先搭建好开发环境。首先确保Node.js已安装。建议修改镜像地址为淘宝镜像源,以加快包裹下载速度。接着安装必要的开发工具:
npm install webpack -gnpm install vue-cli -gvue create 项目名(选择router、Vuex和Babel插件,建议不选择ESLint以减少配置复杂度)vue uinpm run build后将dist目录上传至服务器在单页面应用中,路由配置是必不可少的。确保在项目创建时选择了Router插件。
路由配置文件位于src/router/index.js。以下是一个典型的路由配置示例:
import Vue from 'vue' import VueRouter from 'vue-router' import Test1 from '../views/test1.vue' import Test2 from '../views/test2.vue' Vue.use(VueRouter) const routes = [ { path: '/', redirect: '/test1' }, { path: '/test1', component: Test1 }, { path: '/test2', component: Test2, children: [ { path: '', redirect: 'news' }, { path: 'news', component: () => import('../components/Test2News.vue') }, { path: 'sports', component: () => import('../components/Test2Sports.vue') } ] }, { path: '/test3/:id', component: () => import('../views/test3.vue') }, { path: '/profile', component: () => import('../components/Profile.vue') } ] const router = new VueRouter({ routes }) 在组件中使用Router时,可以使用以下标签:
测试1 测试2 测试3 档案
对应的组件文件如下:
Vuex用于集中管理组件状态,提供一个公共的数据池。确保在项目创建时选择了Vuex插件。
状态管理文件位于src/store/index.js。以下是一个简要的Vuex配置示例:
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { counter: 0 }, mutations: { increment(state) { state.counter++ }, decrement(state) { state.counter-- }, incrementCount(state, count) { state.counter += count } }, actions: { aIncrement(context) { setTimeout(() => { context.commit('increment') }, 1000) } } }) 在组件中使用Vuex状态:
{{ $store.state.counter }} + - +5 建议安装Vue DevTools来更方便地调试Vuex状态。
Axios是Vue推荐的AJAX库,简洁易用,支持浏览器和Node.js环境。
安装命令:npm install axios --save
import axios from 'axios' import App from './App.vue' import router from './router' import store from './store' new Vue({ router, store, render: h => h(App) }).$mount('#app') Axios的使用示例:
axios({ url: 'http://123.207.32.32:8000/home/multidata' }).then(res => { console.log(res) }) 可根据需求配置全局参数:
axios.defaults.baseURL = 'http://123.207.32.32:8000' axios.defaults.timeout = 2000
建议对Axios进行封装,便于维护:
export function request(config) { return axios.create({ baseURL: 'http://123.207.32.32:8000' }).call(config) } 转载地址:http://izee.baihongyu.com/