Vue8-Vuex与Router,前端编程基础教程

24 阅读1分钟

const store = new Vuex.Store({

state: { // 组件间共享的数据

todos: [],

},

mutations: { // 唯一进行同步更新状态数据的方法

/**

  • 添加新待办事项

*/

addTodoItem(state, payload) {

state.todos.push({

id: Math.random(),

title: payload.title,

completed: false,

})

},

},

})

export default store

向根实例中注入 store

import Vue from 'vue'

// 引入 store

import store from './store' // import store from './store/index.js'

new Vue({

store, // 注入 store,这样,在所有后代组件中,都可以使用 this.$store 获取 vuex 的 Store 使用

// render: h => h(App),

}).$mount('#app')

在组件中使用 store

  1. this.$store.state.todos // 类似于data拿里面数据

  2. this.$store.commit(mutationType, payload) // 类似于触发事件

  3. this.$store.getters.allChecked // 类似于计算属性

辅助函数

import { mapState, mapGetters, mapMutations, mapActions } from 'vuex' // 解构出来vuex仓库中保存的数据

Vue Router

=============================================================================

SPA


single page application(单页面应用程序),即在整个应用中,只有一个 html 页面,在用户与应用之间实现交互时能够动态更新页面内容。

前端路由


利用 hash 或 history 改变不会向后端发起新的 html 请求

模式


  1. hash:利用 URL 中 #hash hash 值改变后,不会发送新的网络请求的特点,来实现的路由。使用如 #/home、#/login 类似的方式来表示所请求的前端 URL 资源

  2. history:利用 h5 中 history 新增的 API pushState()、replaceState() 来实现。其路由的格式与服务端路由 URL 格式一致(比 hash 模式来说,没有多余的如 # 之类的符号),这种路由模式要用好,还需要服务端配置

  3. Vue Router是 Vue.js 官方的路由管理器,是一个核心插件,与 Vue.js 高度集成

安装


  • npm安装$ npm i vue-router@3.5.3

  • yarn安装$ yarn add vue-router@3.5.3

定义 VueRouter 对象


import Vue from 'vue'

import VueRouter from 'vue-router'

import Home from '@/views/Home'

import Login from '@/views/Login'

// 使用路由插件

Vue.use(VueRouter)

// 创建 VueRouter 对象

const router = new VueRouter({

mode: 'hash', // 路由模式,可取 hash、history,默认为 hash

routes: [ // 静态路由的配置信息

{

path: '/home', // 当 URL 中访问地址为 /home 时

component: Home, // 拿 Home 组件渲染

},

{

path: '/login',

component: Login,

},

],

})

// 导出路由对象

export default router

在 Vue 组件中使用 VueRouter 时,可使用 VueRouter 提供的两个内置组件:


  1. router-link:链接,相当于

  2. router-view:视图,用于渲染访问路径所对应的组件

  3. 注入 router 到 vue 根实例

// 引入 router

import router from './router'

new Vue({

router,

// render: h => h(App),

}).$mount('#app')

  1. 当在 Vue 根实例中注入了 router 后,在 vue 组件中会自动注入如下两个属性:
  • $router:代表 VueRouter 对象实例

  • $route:代表的是当前激活的路由对象