vue­-router路由和前端状态 管理

vue­-router路由基本加载

可以分为四步 :具体流程如下 :

  • 安装
    在命令行中 进入到自己的项目目录输入一下命令 安装依赖:
npm install --save vue-router  
  • 在需要用到路由跳转的模块中引用(本文是在在入口文件main.js 进行设置)
import router from 'vue-router'
Vue.use(router)

  • 配置路由文件,并在vue实例中注入
// 配置路由
var rt = new router({
    routes: [
        // 可以定义多个路由
        {
            path: '/hello', //指定要跳转的路径
            component: HelloWorld //指定要跳转的组件
        }
    ]
})

/* eslint-disable no-new */
new Vue({
    el: '#app',
    // 注入到实例
    router: rt,
    components: { App },
    template: '<App/>'
})
  • 确定视图加载的位置
 <router-view></router-view>
image.png

具体代码:


GIFx.gif

vue-­router路由的跳转

首先在路由模块router中定义路由


定义要跳转的组件:
image.png

开始跳转
image.png

效果动图:
GIF动图.gif

vue-router路由参数的传递

第一步

  • 一.必须在路由内加入路由的name
  • 二.必须在path后加/: +传递的参数
// 不论在那个模块中使用 必须首先引入
import Vue from 'vue'
import router from 'vue-router'
import HelloWorld from '../components/HelloWorld'
import HelloEarth from '../components/HelloEarth'
// 使用
Vue.use(router)

// 配置路由 ----- export default   一个模块像被其他模块引用 首先要导出

export default new router({
    routes: [
        // 可以定义多个路由
        { 
//定义name
            name: 'helloworld',
            path: '/helloworld/:worldmsg', //指定要跳转的路径 /: 后面是要传递的参数
            component: HelloWorld //指定要跳转的组件
        }, {
//定义name
            name: 'helloearth',
            path: '/helloearth/:earthmsg', //指定要跳转的路径 /: 后面是要传递的参数
            component: HelloEarth //指定要跳转的组件
        },

    ]
})
第二步 在:to后面设置 需要传递的参数
<template>
    <ul>
        <li>
            <!-- 在:to后面设置 需要传递的参数 -->
            <router-link :to="{name:'helloworld',params:{worldmsg:'你好时节'}}">Hello World</router-link>
        </li>
        <li>
             <router-link :to="{name:'helloearth',params:{earthmsg:'你好地丢'}}">Hello Earth</router-link>
        </li>
    </ul>
</template>
<script>
export default {
    name : "list"
}
</script>
<style lang="">
    
</style>
第三步渲染到页面上

固定格式为:
读取参数: $route.params.XXX

 <h3>{{$route.params.worldmsg}}</h3>
  <h3>{{$route.params.earthmsg}}</h3>

Axios之get请求详解

可以分为几步:具体如下

  • 安装
npm install axios
  • 在项目中引入加载
import axios from 'axios'
  • 将axios全局挂载到Vue实例上
    $http是你自己起的名字
Vue.prototype.$http = axios
  • 发送请求 (此处以cnode社区api为例)
    使用CNODE社区官方的API为例展开学习
    获取主题列表API:https://cnodejs.org/api/v1/topics
    参数:page页码
    limit 每页显示的数量
//使用传统的function
<template>
  <div class="hello">
   <H3>我是axios  用来发送请求 和 拦截响应</H3>
   <button @click="getData">发送请求</button>
   <ul>
     <li v-for="(item,index) in  items" :key="index">
       {{item.title}}
     </li>
   </ul>
  </div>
</template>

<script>
// 下面用到了Vue 首先要引入 
import Vue from 'vue'
// 第一步 首先要安装  npm install axios
// 第二部 引入
import axios from 'axios'
// 第三步 将axios全局挂载到VUE原型上 $.后面随便命名 
Vue.prototype.$http = axios
export default {
  name: 'HelloWorld',
  data () {
    return {
     items : []
    }
  },
  methods: {
    // 发送请求 拦截响应的过程 当点击按钮时 请求 cnede社区主页内容 
    getData(){
      var self = this;
      // 可以设置参数  在url后面设置  也可以在链接上设置参数   ?page:1&limit:10
      this.$http.get('https://cnodejs.org/api/v1/topics',{
        params:{
          page:1,
          limit:10
        }
      })
      .then(function(res){
        // 注意此处的this不是当前的Vue实例 需要在前面赋值一下 注意 后台请求的数据是数组  需要遍历一下  在进行操作    this es6语法 则会直接继承父元素 .then(res=>{this.items = res.data.data  console.log(res.data.data})
        self.items = res.data.data
            console.log(res.data.data)
      })
      .catch(function(err){
        console.log(err)
      })
    }
  },
}
</script>

可以设置参数 在url后面设置 也可以在链接上设置参数 ?page:1&limit:10

.then(function(res){
        // 注意此处的this不是当前的Vue实例 需要在前面赋值一下 注意 后台请求的数据是数组  需要遍历一下  在进行操作    this es6语法 则会直接继承父元素 .then(res=>{this.items = res.data.data  console.log(res.data.data})
        self.items = res.data.data
            console.log(res.data.data)
      })
      .catch(function(err){
        console.log(err)
      })

Axios之post请求详解

POST传递数据有两种格式:
form-­data ?page=1&limit=48
x­www-­form­-urlencoded { page: 1,limit: 10 }
axios中,post请求接收的参数必须是form-­data
要安装qs插件—­qs.stringify
具体如下:
在当前项目中安装qs插件

npm install qs

在当前项目模块中引入

import qs from 'qs'
postData(){
      var self = this;
      // 可以设置参数  在url后面设置  也可以在链接上设置参数   ?page:1&limit:10
      this.$http.post('https://cnodejs.org/api/v1/topics',qs.stringify(
        {
          page:1,
          limit:10
        }
      ))
      .then(function(res){
        // 注意此处的this不是当前的Vue实例 需要在前面赋值一下 注意 后台请求的数据是数组  需要遍历一下  在进行操作    this es6语法 则会直接继承父元素 .then(res=>{this.items = res.data.data  console.log(res.data.data})
        self.items = res.data.data
            console.log(res.data.data)
      })
      .catch(function(err){
        console.log(err)
      })
    },
  },

Vuex之store

用来管理状态,共享数据,在各个组件之间管理外部状态,应用场景 大型电商项目各个单页面中共有的 登录显示状态
如何使用?

  • 首先安装插件:
    注意 install可以简写为 num i vuex
npm i vuex
  • 第二步 在入口文件min.js引入vuex,并通过use方法使用它
    import Vuex from 'vuex'
    Vue.use(Vuex)
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
import Vuex from 'vuex'
Vue.use(Vuex)


    // 创建状态仓库 
var store = new Vuex.Store({
        state: {
            num: 88
        }
    })
    Vue.config.productionTip = false
    /* eslint-disable no-new */
new Vue({
    el: '#app',
    router,
    // 注入
    store,
    components: { App },
    template: '<App/>'
})

  • 第三步 创建状态管理仓库 并在实例中注入
 // 创建状态仓库 
var store = new Vuex.Store({
        state: {
            num: 88
        }
    })
    Vue.config.productionTip = false
    /* eslint-disable no-new */
new Vue({
    el: '#app',
    router,
    // 注入
    store,
    components: { App },
    template: '<App/>'
})
  • 第四步 通过this.$sore.state.XXX直接拿到需要的数据
    注意本例状态管理设置为 num :88
<template>
  <div>
    我是组件outter中的全局状态{{outNum}}
  </div>
</template>
<script>
export default {
  name: 'outter',
  computed: {
    outNum: function () {
//直接通过this.$sore.state.XXX拿到全局状态 88
      return this.$store.state.num
    }
  },
}
</script>
<style lang="">
</style>
全局状态
Vuex的相关操作

vuex状态管理的流程
view———­>actions(可包含异步)———–>mutations(只能同步)—–>state————­>view
除了能够获取状态如何改变状态呢?小栗子:

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
    // 创建状态仓库 
export default new Vuex.Store({
    state: {
        num: 88
    },
    // 改变状态 但是mutation只能包含同步操作
    mutations: {
        // increase: function(state) {

        // } 下面是es6语法:
        increase(state) {
            state.num++
        },
        decrease(state) {
            state.num = state.num - 30
        }
    },
    // actions只能对mutations操作 actions可以包含异步操作,但是mutation只能包含同步操作
    actions: {
        // context 上下文对象
        decreaseAction(context) {
            // actions可以包含异步操作
            //   setTimeout(function() {
            //       context.commit('decrease')
            //   }, 1000)
            context.commit('decrease')
        }
    },
    // 处理状态
    getters: {
        getNum(state) {
            return state.num > 0 ? state.num : 0;

        }
    }
})


调用 :
this.$store.commit(increase);
此处的increase是你在mucations中定义的方法名


注意:actions提交的是mutation,而不是直接变更状态
actions可以包含异步操作,但是mutation只能包含同步操作

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,826评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,968评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,234评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,562评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,611评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,482评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,271评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,166评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,608评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,814评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,926评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,644评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,249评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,866评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,991评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,063评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,871评论 2 354

推荐阅读更多精彩内容