vue-router( route, routes, router区别) + vuex和axios的基本用法

it2022-05-05  151

**

vue-router:

**  路由中有三个基本的概念 route, routes, router。

1, route,它是一条路由,由这个英文单词也可以看出来,它是单数, Home按钮 => home内容, 这是一条route, about按钮 => about 内容, 这是另一条路由。

2, routes 是一组路由,把上面的每一条路由组合起来,形成一个数组。[{home 按钮 =>home内容 }, { about按钮 => about 内容}]

3, router 是一个机制,相当于一个管理者,它来管理路由。因为routes 只是定义了一组路由,它放在哪里是静止的,当真正来了请求,怎么办? 就是当用户点击home 按钮的时候,怎么办?这时router 就起作用了,它到routes 中去查找,去找到对应的 home 内容,所以页面中就显示了 home 内容。

4,客户端中的路由,实际上就是dom 元素的显示和隐藏。当页面中显示home 内容的时候,about 中的内容全部隐藏,反之也是一样。客户端路由有两种实现方式:基于hash 和基于html5 history api. ​ 在 src目录下的router/index.js定义router, 就是定义 路径到 组件的 映射。

import Vue from "vue"; import VueRouter from "vue-router"; // 要告诉 vue 使用 vueRouter Vue.use(VueRouter); //1.引入组件 import Bar from '@/views/bar.vue' //2.定义路由 const routes = [ { path:'/bar',name:'bar',component:Bar} ] //3.创建router实例,然后传'routes'配置 const router = new VueRouter({ routes // (缩写)相当于 routes: routes }) //4.创建和挂载根实例。通过router配置参数注入路由 const app = new Vue({ router }).$mount('#app')

显示

<!-- 使用router-link组件来导航 --> <!-- 通过传入 'to' 属性指定链接--> <router-link to="/bar">CAOJIALI</router-link> <!-- 路由出口 --> <!-- 路由匹配到的组件将渲染在这里 --> <router-view></router-view>

嵌套路由

routes: [{ path: '/user/:id', component: User, children: [ // 匹配 /user/:id { path: '', component: UserHome }, // 匹配 /user/:id/profile { path: 'profile', component: UserProfile }, // 匹配 /user/:id/posts { path: 'posts', component: UserPosts } ] }]

**

vuex(vue状态管理)

** 在 src目录下的store/index.js定义router, 就是定义 路径到 组件的 映射。

import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); //创建Vuex实例 const store=new Vuex.Store({ //数据保存在这里,页面通过 this.$store.state来获取 可取出 state:{ count:1 }, //Getter相当于vue中的computed计算属性 getters:{ getStateCount:function(state){ return state.count+1; } } }) export default store //导出store

在main.js文件中引入该文件,在文件里面添加 import store from ‘./store’;,再在vue实例全局引入store对象; Mutations: 数据我们在页面是获取到了,但是如果我们需要修改count值怎么办?如果需要修改store中的值唯一的方法就是提交mutation来修改,我们现在Hello World.vue文件中添加两个按钮,一个加1,一个减1;这里我们点击按钮调用addFun(执行加的方法)和reductionFun(执行减法的方法),然后在里面直接提交mutations中的方法修改值: 修改index.js文件,添加mutations,在mutations中定义两个函数,用来对count加1和减1,这里定义的两个方法就是上面commit提交的两个方法如下: vuex和全局对象的区别

1)Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。

2)你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们能够实现一些工具帮助我们更好地了解我们的应用

补:监听vuex变化 在头部组件里面写监听事件,监听用户名改变时,随着变化

watch:{ '$store.state.userName':function(){ //监听vuex中userName变化而改变header里面的值 this.userName=this.$store.state.userName; } },

axios

在main.js中引用 import Axios from 'axios' import qs from 'qs' //跨域post实例;用到qs组件来避开ajax信使请求;并兼容安卓; Vue.prototype.$qs = qs; // 给对象一个原型挂载属性(很重要) Vue.prototype.$axios = Axios; Axios.defaults.baseURL = 'http://v.jspang.com:8088';

在页面中:

created(){ this.$axios.post("/baixing/wxmini/homePageBelowConten") .then(res=>{ console.log(res) }) .catch(err=>{ console.log(err) }) },

可以使用async await进行封装api接口


最新回复(0)