Vue教程 第三篇 vue-router和vuex

本文深入探讨Vue Router的配置、路由嵌套、跳转方式及传参技巧,同时解析Vuex状态管理,包括store配置、组件间数据共享及与本地存储的对比。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

相较于这两个插件的使用方式来说,对这两个插件的理解更加重要,初学者一定要先理解他们适用的场景,才能明白他们各自存在的意义。大家还是多百度下概念吧,进而在看配置语法,都不会太难。

vue-router

这里我只讲他们的核心点,也是大家开发会面临的问题点。

第一点,路由的配置,自己百度,我要说的是路由的嵌套,也就是二级路由的配置,大家要注意怎么写,还有就是什么时候才考虑使用路由嵌套。

router.js

import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import testStore from '@/components/testStore'
import news from '@/components/news'
import detail from '@/components/detail'

Vue.use(Router)

export default new Router({
  routes: [{
    path: '/HelloWorld',
    name: 'HelloWorld',
    component: HelloWorld
  },
  {
    path: '/testStore',
    name: 'testStore',
    component: testStore
  },
  {
    path: '/news',
    name: 'news',
    component: news,
    children: [{
      // path: '/detail/:id',
      path: '/detail',
      name: 'detail',
      component: detail
    }]
  }
  ]
})

第二点,路由的跳转方式,我们可以以<router-link>标签来做页面html部分的跳转,以this.$router.push、this.$router.replace和this.$router.go来做js部分的跳转,他们有啥区别,自己百度吧。

<template>
  <div id="app">
    <img src="./assets/logo.png">
    <h1>首页</h1>
    <router-link to="HelloWorld">HelloWorld</router-link>
    <router-link to="testStore">testStore</router-link>
    <router-link to="news">news</router-link>
    <router-view/>
  </div>
</template>

<script>
export default {
  name: 'App',
  methods: {

  }
}
</script>

<style>
#app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
.router-link-active{
  color:blue;
}
</style>

第三点,路由跳转传参,这里附一个连接给大家https://segmentfault.com/a/1190000012393587

news.vue和detail.vue

<template>
 <div class="app-container">
   <h3>新闻专栏</h3>
   <div>{{list}}</div>
   <h4>{{count}}</h4>
   <div style="background:#ccc">
    <h4>商品1</h4>
     <button @click="goNewsParams(123)">点击查看商品详情</button>
    </div>
    <div style="background:#ccc">
    <h4>商品2</h4>
     <button @click="goNewsQuery(124)">点击查看商品详情</button>
    </div>
    <router-view></router-view>
 </div>
</template>

<script type="text/ecmascript-6">
export default {
  name: 'news',
  components: {

  },
  data () {
    return {

    }
  },
  computed: {
    list () {
      return this.$store.getters.filteredList
    },
    count () {
      return this.$store.state.count
    }
  },
  watch: {

  },
  methods: {
    goNewsParams (id) {
      // this.$router.push({
      //   path: `/detail/${id}`
      // })

      this.$router.push({
        name: 'detail',
        params: {
          id: id
        }
      })
    },
    goNewsQuery (id) {
      this.$router.push({
        path: '/detail',
        query: {
          id: id
        }
      })
    }
  },
  created () {

  },
  mounted () {

  }
}
</script>

<style scoped>

</style>
<template>
 <div class="app-container">
   <h6 v-if="this.$route.params.id">商品详情  该商品id={{this.$route.params.id}}</h6>
   <h6 v-else>商品详情  该商品id={{this.$route.query.id}}</h6>
 </div>
</template>

<script type="text/ecmascript-6">
export default {
  name: 'detail',
  components: {

  },
  data () {
    return {

    }
  },
  computed: {

  },
  watch: {

  },
  methods: {

  },
  created () {

  },
  mounted () {

  }
}
</script>

<style scoped>

</style>

相信这些案例应该已经说明这三种用法,但是要注意的地方是他们的区别:

1.传参我还是建议可以使用params和query两种方式。
2.使用params传参只能用name来引入路由,即push里面只能是name:’xxxx’,不能是path:’/xxx’,因为params只能用name来引入路由,如果这里写成了path,接收参数页面会是undefined!!!。
3.使用query传参使用path来引入路由。
4.params是路由的一部分,必须要在路由后面添加参数名。query是拼接在url后面的参数,没有也没关系。
5.二者还有点区别,直白的来说query相当于get请求,页面跳转的时候,可以在地址栏看到请求参数,而params相当于post请求,参数不会再地址栏中显示。

vuex

vuex这个插件到底是干啥用的,不用我说了吧,专业来说是整个vue单页项目的状态管理,其实也就是管理整个项目的数据以及做一些项目业务层面上的逻辑处理。其实这个时候大家就该想到有哪些数据需要vuex来管理呢?一般说来有用户登录信息、组件传参数据、以及一些业务逻辑处理。其实上面的案例computed中就有this.$store的写法,这里我们再看下在main.js中的配置(其实也可以像router一样,另外建个文件store.js来管理,达到代码解耦的效果)。

main.js

// 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)

const store = new Vuex.Store({
  state: {
    count: 0,
    list: [1, 5, 8, 10, 30, 50]
  },
  mutations: {
    increment (state, n = 1) {
      state.count += n
    }
  },
  actions: {
    incrementAction (context) {
      context.commit('increment')
    }
  },
  getters: {
    filteredList: state => {
      return state.list.filter(item => item < 10)
    },
    listCount: (state, getters) => {
      return getters.filteredList.length
    }
  }
})

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  components: { App },
  template: '<App/>'
})

testStore.vue

<template>
 <div class="app-container">
   <h3>测试vuex</h3>
   <div>{{list}}</div>
   <div>{{listCount}}</div>

   <h4>{{count}}</h4>
    <button @click="handle">+1</button>
 </div>
</template>

<script type="text/ecmascript-6">
export default {
  name: 'component-name',
  components: {

  },
  data () {
    return {

    }
  },
  computed: {
    list () {
      return this.$store.getters.filteredList
    },
    listCount () {
      return this.$store.getters.listCount
    },
    count () {
      return this.$store.state.count
    }
  },
  watch: {

  },
  methods: {
    handle () {
      this.$store.dispatch('incrementAction')
    }
  },
  created () {

  },
  mounted () {

  }
}
</script>

<style scoped>

</style>

大家可以看到testStore.vue和news.vue组件对变量count的显示是同步的,另外testStore.vue中还有this.$store.dispatch的方法,这里我们来说下main.js中store对象三层结构的理解,state数据层,mutations操作层,actions业务层,很像一种与开发者的约定,所涉及改变数据的,就使用mutations,存在业务逻辑的,就用actions,其实我这么说完,后台人应该会觉得像springMVC的三层结构,道理差不多,所以这里的$store.dispatch写法,其实就是在触发action,最终去改变state里的数据,达到改变整个项目数据效果。当然vuex还有一些进阶的用法,这里不做讲解了,大家可以结合开源项目和官方文档(https://vuex.vuejs.org/zh-cn)去理解。

最后,关于vuex的效果,大家可能会有这样的疑问,他到底和浏览器本地存储的区别是啥?

1.区别:vuex存储在内存,localstorage(本地存储)则以文件的方式存储在本地,永久保存;sessionstorage( 会话存储 ) ,临时保存。localStorage和sessionStorage只能存储字符串类型,对于复杂的对象可以使用ECMAScript提供的JSON对象的stringify和parse来处理

2.应用场景:vuex用于组件之间的传值,localstorage,sessionstorage则主要用于不同页面之间的传值。

3.永久性:当刷新页面(这里的刷新页面指的是 --> F5刷新,属于清除内存了)时vuex存储的值会丢失,sessionstorage页面关闭后就清除掉了,localstorage不会。  

注:很多同学觉得用localstorage可以代替vuex, 对于不变的数据确实可以,但是当两个组件共用一个数据源(对象或数组)时,如果其中一个组件改变了该数据源,希望另一个组件响应该变化时,localstorage,sessionstorage无法做到,原因就是区别1。

总结说来,真正的实战中,我们是会把二者结合使用的,也就是说在vuex的store中写入state数据的同时也同步存储到浏览器中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值