vuex和router的使用

vuex的基础使用

在使用vuex前要注意,只有中大型单页面项目才使用vuex来管理数据,而http请求使用axios来请求

vuex

  • state,驱动应用的数据源;
  • view,以声明方式将 state 映射到视图;
  • actions,响应在 view 上的用户输入导致的状态变化。

state、view、actions可以看成一个仓库store

在这里单单讲基本的使用

index.js

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

export default new Vuex.Store({
	state:{//数据层
		city:'上海'
	},
	actions:{//调用行为
		changeCity(ctx,city){//ctx是用来使用方法的
			ctx.commit('changeCity',city)
		}
	},
	mutations:{//视图层改变数据
		changeCity(state,city){
			state.city = city
		}
	}
})

组件中使用 

{{this.$store.state.city}}//在vue中这样使用获得veux中city的数据
this.$store.dispatch('changeCity',city)//结合图来看,dispatch是使用在actions中的方法

注意!实际上如果数据不需要进行异步操作或者批量操作的话是不需要用到actions中的方法的,可以直接访问mutations改变数据显示的内容。可以直接使用。

this.$store.commit('changeCity',city)//不经过actions中的方法,直接到mutations

vuex的高级使用 

1.localStorage

vuex中需要时常需要使用localStorage,使用的时候必须加try{  }catch(e){}防止出现错误的时候,代码不运行

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

let defaultCity = '上海';
try{
	if(localStorage.city){//如果有这个缓存就替换,如果没有或不支持就不运行
		defaultCity = localStorage.city
	}
}catch(e){}
export default new Vuex.Store({
	state:{},
	actions:{},
	mutations:{
		changeCity(state,city){
			try{
				localStorage.city = city
			}catch(e){}
			//使用localStorage必须使用try..catch
	}
	}
})

 2.vuex结构的优化

结构优化

import Vue from 'vue'
import Vuex from 'vuex'

import state from './state.js'//文件所在位置,下方有图
import actions from './actions.js'
import mutations from './mutations.js'
Vue.use(Vuex)


export default new Vuex.Store({
	state,
	actions,
	mutations
})

文件结构 

state.js

let defaultCity = '上海';
try{
	if(localStorage.city){
		defaultCity = localStorage.city
	}
}catch(e){}

//可以在暴露前书写js代码


export default{
	city:defaultCity//原来state放的内容,只不过需要暴露出来,actions.js ,mutations.js同理
}

代码优化 

在组件中使用

import { mapState,mapMutations ,mapGetter} from 'vuex'

computed:{
    ...mapState(['city'])//city是state中数据的名字
    //就可以把刚刚的{{this.$store.state.city}}换成{{this.city}}
},
methods:{
    ...mapMutations(['functionName']
    //就可以把刚刚的   this.$store.commit('changeCity',data)换成this.changeCity(data)
    ...mapGetter(['functionName'])
    //类似于计算属性。 直接用this.functionName使用
}

 <keep-alive>

<keep-alive>//相当于缓存,不会再执行mounted的钩子了
    <router-view></router-view>
<keep-alive>
//但在页面打开会执行activated钩子,关闭会执行deactivated钩子。可以用于解绑全局事件不影响到其他组件。window.addEventLister() 全局事件,如果不关闭在所有组件都会触发

路由的跳转

1.使用router-link的a标签跳转 

<router-link to="adress"></router-link>

2.使用路由方法跳转 (编程式导航)

this.$router.push('adress')//看vue-router比较详细
this.$router.push(path:'adress')//path为跳转的路径
this.$router.push(name:'Name')//name为路由的名字,在index.js中配置

this.$router.push(path:'adress',parmas:'传的参数')
this.$router.push(path:'adress/aid=xxx')//动态路由跳转
this.$router.push(path:'adress?aid=xxx')//get跳转

3.路由的配置

router -->  index.js

import Vue from 'vue';
import Router from 'vue-router';
import Home from '@/Pages/home/Home.vue';
import List from '@/Pages/city/City.vue';

Vue.use(Router);

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home,
    },{
      path: '/city',
      name: 'City',
      component: List,
    },
  ],
});
//组件中使用<router-link to="/city"><router-link>

4.动态路由设置

import Vue from 'vue';
import Router from 'vue-router';
import Home from '@/Pages/home/Home.vue';
import City from '@/Pages/city/City.vue';
import Detail from '@/Pages/detail/Detail.vue';

Vue.use(Router);

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home,
    },{
      path: '/city',
      name: 'City',
      component: City,
    },{
      path: '/detail/:id',
      name: 'Detail',
      component: Detail,
    },
    { path:'*', redirect: '/' },   /*默认跳转路由,若路由未匹配到,则默认跳转到根组件中*/
  ],
});
//动态路由传值
//组件中使用<router-link :to=" '/detail/' + item.id"><router-link> //item.id是动态的

//路由的get传值
//组件中使用<router-link :to=" '/detail?id =' + item.id"><router-link> //item.id是动态的

 to有冒号!!!! 

页面获取动态路由的值

var objParams = this.$route.params;
//再mounted:{}中获取到参数

页面获取路由get传值

var objParams = this.$route.query;
//再mounted:{}中获取到参数

5.嵌套路由,用于同页面之间路由的改变。(例如点击左侧,右侧内容改变)。

1.添加子组件

最好是在user.vue下加组件方便识别 ,profile,posts这俩组件就是右侧的不同路由下的内容

routes: [
    { path: '/user/:id', component: User,//这里是父路由
      children: [
        //子路由列表
        {
          path: 'profile',
          component: UserProfile
        },
        {
          path: 'posts',
          component: UserPosts
        }
      ]
    }
  ]

设置完成组件后,需要在父组件中添加<router-view></router-view>来显示内容;

嵌套命名视图

嵌套路由需要子路由,如果想要设置成同级路由就可以设置index.js成


  routes: [
    {
      path: '/',
      components: {
        default: Foo,
        a: Bar,
        b: Baz
      }
    }
  ]

设置显示路由组件为

<router-view></router-view>
<router-view name="a"></router-view>
<router-view name="b"></router-view>
//根据name的不同显示不同的内容

捕获 所有路由路径,或者404页面

//匹配的时候有优先级,自上而下,最上面优先级最高
{
  // 会匹配所有路径
  path: '*',
  components: {
    404
  }
}
{
  // 会匹配以 `/user-` 开头的任意路径
  path: '/user-*'
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值