面试题答案
一键面试1. 安装 Vuex 和 Vue Router
在项目根目录下,通过 npm 或 yarn 安装:
# npm
npm install vuex vue-router --save
# yarn
yarn add vuex vue-router
2. 集成 Vuex
创建 Vuex 模块
在项目 src
目录下创建 store
文件夹,在 store
文件夹中创建 index.js
文件,内容如下:
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
// 创建 state
const state = {
count: 0
};
// 创建 mutations
const mutations = {
increment(state) {
state.count++;
}
};
// 创建 actions
const actions = {
increment({ commit }) {
commit('increment');
}
};
// 创建 getters
const getters = {
getCount(state) {
return state.count;
}
};
export default new Vuex.Store({
state,
mutations,
actions,
getters
});
在 Vue 项目中使用 Vuex
在 main.js
中引入并挂载 Vuex:
import Vue from 'vue';
import App from './App.vue';
import store from './store';
Vue.config.productionTip = false;
new Vue({
store,
render: h => h(App)
}).$mount('#app');
3. 集成 Vue Router
配置 Vue Router 的路由表
在 src
目录下创建 router
文件夹,在 router
文件夹中创建 index.js
文件,内容如下:
import Vue from 'vue';
import Router from 'vue-router';
import Home from '../views/Home.vue';
import About from '../views/About.vue';
Vue.use(Router);
const routes = [
{
path: '/',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
component: About
}
];
const router = new Router({
mode: 'history',
routes
});
export default router;
在 Vue 项目中使用 Vue Router
在 main.js
中引入并挂载 Vue Router:
import Vue from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';
Vue.config.productionTip = false;
new Vue({
store,
router,
render: h => h(App)
}).$mount('#app');
4. 在组件中调用 Vuex 的状态和 Vue Router 的导航方法
调用 Vuex 的状态
在组件中,可以通过 mapState
、mapGetters
、mapMutations
、mapActions
辅助函数来调用 Vuex 的状态、getters、mutations 和 actions。例如在 Home.vue
中:
<template>
<div>
<p>Count: {{ count }}</p>
<button @click="increment">Increment</button>
</div>
</template>
<script>
import { mapState, mapActions } from 'vuex';
export default {
computed: {
...mapState(['count'])
},
methods: {
...mapActions(['increment'])
}
};
</script>
调用 Vue Router 的导航方法
在组件中,可以通过 this.$router
来调用导航方法。例如在 Home.vue
中跳转到 About
页面:
<template>
<div>
<button @click="goToAbout">Go to About</button>
</div>
</template>
<script>
export default {
methods: {
goToAbout() {
this.$router.push('/about');
}
}
};
</script>