【日常学习】Vue路由

一、Vue-router 路由


1.1 介绍

Vue Router 是 Vue.js 官方的路由管理器。它和 Vue.js 的核心深度集成,让构建单页面应用变得易如反掌

1.2 准备工作

创建工程,并安装路由模块

vue create router-app 
router-app> npm install vue-router -s
1.3 Router 入门

1.在src下创建views文件夹,然后创建Home和About两个组件

<template>
    <div>
        <h1>Home</h1>
    </div>
</template>

<script>
    export default {
        name: "Home"
    }
</script>

<style scoped>

</style>
<template>
    <div>
        <h1>About</h1>
    </div>
</template>

<script>
    export default {
        name: "About"
    }
</script>

<style scoped>

</style>

2.在src下创建router文件夹,然后在里面定义一个index.js文件,在index.js文件中配置路由信息:

import Vue from 'vue'
import Router from 'vue-router'

import Home from "../views/Home";
import About from "../views/About";

Vue.use(Router)   //使用插件

export default new Router({

    routes: [
        {
            path: '/home',
            component: Home,
        },
        {
            path: '/about',
            component: About
        },
    ]

})

3.修改main.js

import Vue from 'vue'
import App from './App.vue'

//默认指向router目录下的index.js
import router from './router'

Vue.config.productionTip = false

new Vue({
  router,//配置router
  render: h => h(App),
}).$mount('#app')

4.修改App.vue

<template>

  <div id="app">
    <ul>
      <li>
        <router-link to="/home">Home</router-link>
      </li>
      <li>
        <router-link to="/about">About</router-link>
      </li>
    </ul>

    <hr>

    <!-- 设置路由显示 -->
    <div>
      <router-view></router-view>
    </div>
  </div>

</template>

<script>
//import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'App',
  components: {
    //HelloWorld
  }
}
</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;
}
</style>

5.访问浏览器进行测试即可

6.设置默认访问Home页面,修改index.js

import Vue from 'vue'
import Router from 'vue-router'

import Home from "../views/Home";
import About from "../views/About";

Vue.use(Router)   //使用插件

export default new Router({

    routes: [
        {
            path: '/home',
            component: Home,
        },
        {
            path: '/about',
            component: About
        },
        {
            path: '/',
            redirect: '/home'
        },
    ]

})

7.浏览器访问:localhost:8080,会显示Home页面,显示后路径会跳转为:localhost:8080/#/home,有#号

我们向router实例中添加mode属性:

  • 值"hash": url带# 适用于调试模式
  • 值"history" url不带#
import Vue from 'vue'
import Router from 'vue-router'

import Home from "../views/Home";
import About from "../views/About";

Vue.use(Router)   //使用插件

export default new Router({
    mode:'history',
    routes: [
        {
            path: '/home',
            component: Home,
        },
        {
            path: '/about',
            component: About
        },
        {
            path: '/',
            redirect: '/home'
        },
    ]

})

8.再次访问浏览器进行测试即可

1.4 子路由

1.在src/views目录下创建about目录,然后再创建Info.vue组件

<template>
    <div>
        <h1>Info</h1>
    </div>
</template>

<script>
    export default {
        name: "Info"
    }
</script>

<style scoped>

</style>

2.在index.js导入Info.vue组件并配置children子路由

import Vue from 'vue'
import Router from 'vue-router'

//导入组件,一次性全部加载
// import Home from "../views/Home";
// import About from "../views/About";
// import Info from "../views/about/Info";

//实际开发中,一般使用按需加载的方式
const Home = () => import('../views/Home');
const About = () => import('../views/About');
const Info = () => import('../views/about/Info');


Vue.use(Router)   //使用插件

export default new Router({
    mode:'history',
    routes: [
        {
            path: '/home',
            component: Home,
        },
        {
            path: '/about',
            component: About,
            children:[
                {
                    path:'/about/info',
                    component:Info
                }
            ]
        },
        {
            path: '/',
            redirect: '/home'
        },
    ]

})

3.修改About.vue组件

<template>
<!--    <div>-->
<!--        <h1>About</h1>-->
<!--    </div>-->

    <div>
        <center>
        <table border="1" cellpadding="0" cellspacing="0" width="200">
            <tr>
                <th>id</th>
                <th>name</th>
            </tr>
            <tr>
                <td>1</td>
                <td>
                    <router-link to="/about/info">jack</router-link>
                </td>
            </tr>
            <tr>
                <td>2</td>
                <td>
                    rose
                </td>
            </tr>
        </table>

        <router-view></router-view>
        </center>
    </div>

</template>

<script>
    export default {
        name: "About"
    }
</script>

<style scoped>

</style>

访问浏览测试即可

1.5 路由传参

1.修改index.js,在路径上配置 id和name 以及props

import Vue from 'vue'
import Router from 'vue-router'

//导入组件,一次性全部加载
// import Home from "../views/Home";
// import About from "../views/About";
// import Info from "../views/about/Info";

//实际开发中,一般使用按需加载的方式
const Home = () => import('../views/Home');
const About = () => import('../views/About');
const Info = () => import('../views/about/Info');


Vue.use(Router)   //使用插件

export default new Router({
    mode:'history',
    routes: [
        {
            path: '/home',
            component: Home,
        },
        {
            path: '/about',
            component: About,
            children:[
                {
                    path:'/about/info/:id/:name',
                    component:Info,
                    props:true
                }
            ]
        },
        {
            path: '/',
            redirect: '/home'
        },
    ]

})

2.修改Info.vue组件,设置id和name类型

<template>
    <div>
        <h1>Info</h1>
        <h1>{{ id }} -- {{ name }}</h1>
    </div>
</template>

<script>
    export default {
        name: "Info",
        props:{
            id:Number,
            name:String
        }
    }
</script>

<style scoped>

</style>

3.修改About.vue组件,设置参数值

<template>
<!--    <div>-->
<!--        <h1>About</h1>-->
<!--    </div>-->

    <div>
        <center>
        <table border="1" cellpadding="0" cellspacing="0" width="200">
            <tr>
                <th>id</th>
                <th>name</th>
            </tr>
            <tr v-for="(user,index) in users" :key="index">
                <td>{{ user.id }}</td>
                <td>
                    <router-link :to="'/about/info/' + user.id +'/' + user.name">{{ user.name }}</router-link>
                </td>
            </tr>
            <tr>
                <td>2</td>
                <td>
                    rose
                </td>
            </tr>
        </table>

        <router-view></router-view>
        </center>
    </div>

</template>

<script>
    export default {
        name: "About",
        data(){
            return{
                users:[
                    {id:1,name:'张三'},
                    {id:2,name:'李四'},
                    {id:3,name:'王五'},
                ]
            }
        }
    }
</script>

<style scoped>

</style>

4.访问浏览器测试即可

1.6 Element-ui 中的使用

1.切换到工程路径下,安装router

music-app> npm install --save vue-router

2.在src下创建views文件夹,然后创建Music和Sheet两个组件

<template>
    <div>

        <el-dialog
                title="提示"
                :visible.sync="updatedialogVisible"
                width="30%"
                :before-close="handleClose">

            <el-form :model="musicModel" :rules="musicRules" ref="updateForm">
                <el-form-item label="id" prop="musicId">
                    <el-input v-model="musicModel.musicId" readonly="readonly"></el-input>
                </el-form-item>
                <el-form-item label="歌曲" prop="musicName">
                    <el-input v-model="musicModel.musicName"></el-input>
                </el-form-item>
                <el-form-item label="专辑" prop="musicAlbumName">
                    <el-input v-model="musicModel.musicAlbumName"></el-input>
                </el-form-item>
                <el-form-item label="歌手" prop="musicArtistName">
                    <el-input v-model="musicModel.musicArtistName"></el-input>
                </el-form-item>
                <el-form-item label="时间" prop="createTime">
                    <el-date-picker type="date" placeholder="选择日期" v-model="musicModel.createTime" style="width: 100%;"></el-date-picker>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="updateMusic('updateForm')">修改</el-button>
                    <el-button @click="resetForm('updateForm')">重置</el-button>
                </el-form-item>
            </el-form>

        </el-dialog>


        <el-dialog
                title="提示"
                :visible.sync="dialogVisible"
                width="30%"
                :before-close="handleClose">

            <el-form :model="musicModel" :rules="musicRules" ref="musicForm">
                <el-form-item label="id" prop="musicId">
                    <el-input v-model="musicModel.musicId"></el-input>
                </el-form-item>
                <el-form-item label="歌曲" prop="musicName">
                    <el-input v-model="musicModel.musicName"></el-input>
                </el-form-item>
                <el-form-item label="专辑" prop="musicAlbumName">
                    <el-input v-model="musicModel.musicAlbumName"></el-input>
                </el-form-item>
                <el-form-item label="歌手" prop="musicArtistName">
                    <el-input v-model="musicModel.musicArtistName"></el-input>
                </el-form-item>
                <el-form-item label="时间" prop="createTime">
                    <el-date-picker type="date" placeholder="选择日期" v-model="musicModel.createTime" style="width: 100%;"></el-date-picker>
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" @click="submitForm('musicForm')">立即创建</el-button>
                    <el-button @click="resetForm('musicForm')">重置</el-button>
                </el-form-item>
            </el-form>

        </el-dialog>


        <el-button size="mini" type="success" @click="dialogVisible = true">添加</el-button>

        <el-table
                :data="musics"
                border
                style="width: 100%">
            <el-table-column
                    align="center"
                    prop="musicId"
                    label="编号">
            </el-table-column>
            <el-table-column
                    align="center"
                    prop="musicName"
                    label="歌曲名称"
                    width="180">
            </el-table-column>
            <el-table-column
                    align="center"
                    prop="musicAlbumName"
                    label="专辑名称"
                    width="180">
            </el-table-column>
            <el-table-column
                    align="center"
                    prop="musicArtistName"
                    label="歌手名称"
                    width="180">
            </el-table-column>
            <el-table-column
                    align="center"
                    prop="createTime"
                    label="时间"
                    :formatter="formatDate"
                    width="180">
            </el-table-column>

            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button
                            size="mini"
                            type="primary"
                            icon="el-icon-edit"
                            @click="updateById(scope.row.musicId)">编辑</el-button>
                    <el-button
                            size="mini"
                            type="danger"
                            icon="el-icon-delete"
                            @click="deleteById(scope.row.musicId)">删除</el-button>
                </template>
            </el-table-column>

        </el-table>

        <el-pagination
                background
                layout="prev, pager, next"
                :total="total"
                :page-size="pageSize"
                @current-change="toPage">
        </el-pagination>

    </div>
</template>

<script>

    import moment from 'moment'

    export default {
        name: "Music",

        data(){
            return{

                //msg:"hello vue",

                musics:[],
                total:0,
                pageSize:0,
                currentPage:1,
                dialogVisible: false,
                updatedialogVisible:false,

                musicModel: {
                    musicId: '',
                    musicName: '',
                    musicAlbumName: '',
                    musicArtistName: '',
                    createTime: ""
                },
                musicRules: {
                    musicId: [
                        {required: true, message: '请输入id', trigger: 'blur'}
                    ]
                }
            }
        },
        methods:{

            changeMsg(massage){
                alert(massage)
                this.msg = massage;
            },

            formatDate(row,column,currDate){
                return moment(currDate).format("YYYY-MM-DD")
            },
            toPage(currPage){
                //alert(currPage)
                this.axios.get('/music/findByPage?pageNum='+currPage)
                    .then(resp => {
                        // resp.data才是实际的数据本身
                        this.musics = resp.data.list;
                        this.total = resp.data.total;
                        this.currentPage = resp.data.pageNum;
                    })
            },
            deleteById(musicId){

                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {

                    this.axios.get('/music/deleteById?musicId='+musicId)
                        .then(resp => {
                            if(resp.data == "success"){
                                this.toPage(this.currentPage);
                            }
                        })

                    this.$message({
                        type: 'success',
                        message: '删除成功!'
                    });
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },

            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.axios.post('/music/save',this.musicModel)
                            .then(resp => {
                                if(resp.data == "success"){
                                    this.$refs[formName].resetFields();//清空下一次添加表单中的数据
                                    this.dialogVisible = false //关闭添加的对话框
                                    this.toPage(this.currentPage);
                                }
                            })
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },

            updateById(musicId){

                this.updatedialogVisible =true;

                this.axios.get('/music/findById?musicId='+musicId)
                    .then(resp => {
                        this.musicModel = resp.data;
                    })
            },

            updateMusic(){
                this.axios.post('/music/updateMusic',this.musicModel)
                    .then(resp => {
                        if(resp.data == "success"){
                            this.updatedialogVisible = false //关闭添加的对话框
                            this.toPage(this.currentPage);
                        }
                    })
            }

        },
        mounted() {
            //第一种方式
            // let that = this;
            // this.axios.get('/music/findAll')
            //         .then(function (response) {
            //           that.musics = response.data;
            //         })
            //         .catch(function (error) {
            //           console.log(error);
            //         });

            //第二种方式
            // this.axios.get('/music/findAll')
            //         .then(resp => {
            //           // resp.data才是实际的数据本身
            //           this.musics = resp.data;
            //           alert(this.musics)
            //         })

            //第三种方式
            this.$http.get('/music/findByPage').then((response) => {
                this.musics = response.data.list;
                this.total = response.data.total;
                this.pageSize = response.data.pageSize;
                this.currentPage = response.data.pageNum;
            })

        }
    }
</script>

<style scoped>
    .el-pagination {
        text-align: center;
        margin-top: 10px;
    }

    .el-table {
        margin-top: 10px;
    }
</style>
<template>
    <div>
        <h1>歌单列表</h1>
    </div>
</template>

<script>
    export default {
        name: "Sheet"
    }
</script>

<style scoped>

</style>

3.在src下创建router目录,在router目录下创建index.js并编写index.js

import Vue from 'vue'
import Router from 'vue-router'

const Music = () => import("../views/Music")
const Sheet = () => import("../views/Sheet")

Vue.use(Router)   //使用插件

export default new Router({
    mode:'history',
    routes: [
        {
            path: '/music',
            component: Music,
        },
        {
            path: '/sheet',
            component: Sheet
        },
    ]

})

4.在main.js中导入router

import Vue from 'vue'
import App from './App.vue'

//注册组件
import MyComponent from "./components/MyComponent";
Vue.component("MyComponent",MyComponent)

// 如下两个是网络的请求组件
import VueAxios from "vue-axios";
import axios from 'axios'

// ElmentUI的组件
import ElementUI from 'element-ui'
// ElementUI的样式
import 'element-ui/lib/theme-chalk/index.css'

Vue.use(VueAxios, axios)
Vue.use(ElementUI)

// 设置基础的url地址
axios.defaults.baseURL = 'http://localhost:8081'

Vue.config.productionTip = false

import router from './router'//找到router目录下的index.js

new Vue({
  router,//配置router
  render: h => h(App),
}).$mount('#app')

5.修改App.vue

<template>
  <el-container>

<!--    <MyComponent :MyTitle="msg" :MyMethod="changeMsg"></MyComponent>-->

    <el-header>管理系统</el-header>
    <el-container>
      <el-aside>

        <!-- 添加 router ,否则页面无法显示-->
        <el-menu router>
          <!-- element-ui将vue中的router的to属性,使用index来替代了 -->
          <el-menu-item index="/music">
            <template slot="title">
              <i class="el-icon-setting"></i>
              歌曲列表</template>
          </el-menu-item>
          <el-menu-item  index="/sheet">
            <template slot="title"><i class="el-icon-menu"></i>歌单列表</template>
          </el-menu-item>
        </el-menu>
      </el-aside>

      <el-main>

        <!-- 显示内容 -->
        <router-view></router-view>

      </el-main>
    </el-container>

  </el-container>
</template>

<script>
//import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'App',
  components: {
    //HelloWorld
  },

}
</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;
}
</style>

<!-- 设置容器样式 -->
<style>
  .el-header {
    background-color: #409EFF;
    color: #ffffff;
    line-height: 60px;
    font-size: 28px;
  }

  .el-aside {
    background-color: white;
    width: 180px !important;
  }

</style>

6.访问浏览器测试即可

二、路由守卫


2.1 局部路由守卫

在某个页面中对其权限进行判断操作

1.在Music.vue中添加 beforeRouteEnter

export default {

    //to:要去哪里
    //from:从哪里来
    //next:继续向下执行
    beforeRouteEnter:function(to,from,next){
        // alert(to.path);
        // alert(from.path);
        // next();

        let meta = to.meta;
        let flag = false;

        meta.forEach(m =>{
            if(m.indexOf("music:list")>-1){
                flag = true;
            }
        })

            if(flag){
                next();
            }else {
                next({path:'/'});
            }
    }
}

2.在 index.js 中修改routes配置

import Vue from 'vue'
import Router from 'vue-router'

const Music = () => import("../views/Music")
const Sheet = () => import("../views/Sheet")

Vue.use(Router)   //使用插件

export default new Router({
    mode:'history',
    routes: [
        {
            path: '/music',
            component: Music,
            meta:["music:list"]
        },
        {
            path: '/sheet',
            component: Sheet
        },
        {
            path: '/',
            redirect: "/sheet"
        },
    ]

})
2.2 全局路由守卫

在所有页面中对其权限进行判断操作

1.安装vue-cookie

my-app>npm install vue-cookies --save

2.在views目录下创建Login.vue

<template>
<!--    <div>-->
<!--        <h1>登录页面</h1>-->
<!--    </div>-->

    <el-container>
        <el-main>
            <el-row>
                <el-col :span="12" :offset="6">
                    <el-card class="box-card">
                        <div slot="header" class="clearfix">
                            <span>用户登录</span>
                        </div>
                        <div>
                            <el-form :model="loginInfo">
                                <el-form-item label="用户名">
                                    <el-input v-model="loginInfo.username"></el-input>
                                </el-form-item>
                                <el-form-item label="密码">
                                    <el-input v-model="loginInfo.password"></el-input>
                                </el-form-item>
                                <el-form-item>
                                    <el-button type="primary" @click.prevent="login">登录</el-button>
                                </el-form-item>
                            </el-form>
                        </div>
                    </el-card>
                </el-col>
            </el-row>
        </el-main>
    </el-container>

</template>

<script>

    //导入vue-cookies
    import VueCookies from 'vue-cookies'

    export default {
        name: "Login",
        data(){
            return{
                loginInfo:{
                    username:"",
                    password:""
                }
            }
        },
        methods:{
            login(){
                this.axios.post("/user/login",this.loginInfo)
                    .then(resp => {
                        //登录成功后,将token设置到cookie中,然后跳转页面
                        let token = resp.data.token;
                        alert(token)
                        VueCookies.set("token",token);

                        this.$router.push({path:'/index'})
                    })
            }
        }
    }
</script>

<style scoped>

</style>

3.在后端编写Controller

package com.qf.controller;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.UUID;

@RestController
@RequestMapping("user")
@CrossOrigin(origins = "*")
public class UserController {

    @RequestMapping("login")
    public Object login(String username,String password){
        
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", UUID.randomUUID());

        return map;
    }
}

4.创建 Index.vue,将App.vue中的代码都拷贝到 Index.vue中

<template>
    <el-container>

        <!--    <div id="app">-->
        <!--      <MyComponent :MyTitle="msg" :MyMethod="changeMsg"></MyComponent>-->
        <!--    </div>-->

        <el-header>管理系统</el-header>
        <el-container>
            <el-aside>
                <el-menu router>
                    <!-- element-ui将vue中的router的to属性,使用index来替代了 -->
                    <el-menu-item index="/music">
                        <i class="el-icon-setting"></i>歌曲管理
                    </el-menu-item>
                    <el-menu-item index="/sheet">
                        <i class="el-icon-menu"></i>歌单管理
                    </el-menu-item>
                </el-menu>
            </el-aside>
            <el-main>
                <!-- 编写 router-view -->
                <router-view></router-view>
            </el-main>
        </el-container>

    </el-container>
</template>

<script>

    export default {
        name: 'Index',
        components: {
            //HelloWorld
        },


    }
</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;
    }
</style>

<!-- 设置容器样式 -->
<style>
    .el-header {
        background-color: #409EFF;
        color: #ffffff;
        line-height: 60px;
        font-size: 28px;
    }

</style>

5.修改App.vue

<template>
    <router-view></router-view>
</template>

<script>

export default {
  name: 'App',
}
</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;
}
</style>

6.修改router目录下的index.js

import Vue from 'vue'
import Router from 'vue-router'

import VueCookies from 'vue-cookies'

const Music = () => import("../views/Music")
const Sheet = () => import("../views/Sheet")
const Login = () => import("../views/Login")
const Index = () => import("../views/Index")

Vue.use(Router)   //使用插件
Vue.use(VueCookies)

const router = new Router({
    mode:'history',
    routes: [

        {
            path: '/',
            redirect: "/index"
        },
        {
            path: '/login',
            component: Login
        },
        {
            path: '/index',
            component: Index,
            children:[
                {
                    path: '/music',
                    component: Music,
                    meta:["music:list"]
                },
                {
                    path: '/sheet',
                    component: Sheet
                },
            ]
        },
    ]

})

//全局路由守卫
router.beforeEach((to,from,next) => {
    //如果用户访问登录页面 或者 cookie中有token 则放行
    if(to.path.indexOf("/login")>-1 || VueCookies.get("token")){
        next();
    }else {
        next({path:"/login"});
    }
})

export default router;

7.访问浏览器测试即可

三、 Vuex的应用


3.1 Vuex介绍

Vuex 是一个专为 Vue.js 应用程序开发的 状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

3.2 准备工作

1.在项目根目录执行如下命令来安装 Vuex

my-app> npm install vuex --save

2.在main.js 中导入 Vuex

import Vuex from 'vuex'
Vue.use(Vuex);
3.3 配置 vuex

1.在 src 目录下创建一个名为 store 的目录并新建一个名为 index.js 文件用来配置 Vuex

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

// 全局 state 对象,用于保存所有组件的公共数据
const state = {
  // 定义一个 user 对象
  // 在组件中是通过 this.$store.state.user 来获取
  user: {
    name: ''
  }
};

// 实时监听 state 值的最新状态,注意这里的 getters 可以理解为计算属性
const getters = {
  // 在组件中是通过 this.$store.getters.getUser 来获取
  getUser(state) {
    return state.user;
  }
};

// 定义改变 state 初始值的方法,这里是唯一可以改变 state 的地方,缺点是只能同步执行
const mutations = {
  // 在组件中是通过 this.$store.commit('updateUser', user); 方法来调用 mutations
  updateUser(state, user) {
    state.user = user;
  }
};

// 定义触发 mutations 里函数的方法,可以异步执行 mutations 里的函数
const actions = {
  // 在组件中是通过 this.$store.dispatch('asyncUpdateUser', user); 来调用 actions
  asyncUpdateUser(context, user) {
    context.commit('updateUser', user);
  }
};

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

2.修改 main.js 增加刚才配置的 store/index.js,关键代码如下:

import Vue from 'vue'
import Vuex from 'vuex'
import store from './store'

Vue.use(Vuex);

new Vue({
  el: '#app',
  store
});

3.修改Login.vue中的login方法

 methods:{
     login(){
         this.axios.post("/user/login",this.loginInfo)
             .then(resp => {
                 //登录成功后,将token设置到cookie中,然后跳转页面
                 let user = resp.data.token;
                 alert(user)
                 VueCookies.set("token",user);
                 
                 //使用vuex中的store存储返回的User
                 this.$store.dispatch("asyncUpdateUser",user)
				 //跳转页面
                 this.$router.push({path:'/index'})
             })
     }
 }

4.修改Index.vue中的data以及el-header

<template>
    <el-container>

        <!--    <div id="app">-->
        <!--      <MyComponent :MyTitle="msg" :MyMethod="changeMsg"></MyComponent>-->
        <!--    </div>-->

        <el-header>管理系统:{{ user.username }}</el-header>
        <el-container>
            <el-aside>
                <el-menu router>
                    <!-- element-ui将vue中的router的to属性,使用index来替代了 -->
                    <el-menu-item index="/music">
                        <i class="el-icon-setting"></i>歌曲管理
                    </el-menu-item>
                    <el-menu-item index="/sheet">
                        <i class="el-icon-menu"></i>歌单管理
                    </el-menu-item>
                </el-menu>
            </el-aside>
            <el-main>
                <!-- 编写 router-view -->
                <router-view></router-view>
            </el-main>
        </el-container>

    </el-container>
</template>

<script>

    export default {
        name: 'Index',
        components: {
            //HelloWorld
        },

        data(){
            return{
                user:this.$store.getters.getUser
            }
        }

    }
</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;
    }
</style>

<!-- 设置容器样式 -->
<style>
    .el-header {
        background-color: #409EFF;
        color: #ffffff;
        line-height: 60px;
        font-size: 28px;
    }

</style>

5.修改后端代码(需要先创建一个User类)

package com.qf.controller;

import com.qf.pojo.User;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.UUID;

@RestController
@RequestMapping("user")
@CrossOrigin(origins = "*")
public class UserController {

    @RequestMapping("login")
    public Object login(@RequestBody User user){

        System.out.println("UserController:"+user);
        //调用数据库进行判断

        HashMap<String, Object> map = new HashMap<>();
        map.put("token",user);

        return map;
    }

}

访问浏览器进行测试

解决浏览器刷新后 Vuex 数据消失问题
  • 问题描述

Vuex 的状态存储是响应式的,当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。但是有一个问题就是:vuex 的存储的数据只是在页面的中,相当于我们定义的全局变量,刷新之后,里边的数据就会恢复到初始化状态。但是这个情况有时候并不是我们所希望的。

  • 解决方案

监听页面是否刷新,如果页面刷新了,将 state 对象存入到 sessionStorage 中。页面打开之后,判断 sessionStorage 中是否存在 state 对象,如果存在,则说明页面是被刷新过的,将 sessionStorage 中存的数据取出来给 vuex 中的 state 赋值。如果不存在,说明是第一次打开,则取 vuex 中定义的 state 初始值。

  • 修改代码

1.在 App.vue 中增加监听刷新事件

  export default {
    name: 'App',
    mounted() {
      window.addEventListener('unload', this.saveState);
    },
    methods: {
      saveState() {
        sessionStorage.setItem('state', JSON.stringify(this.$store.state));
      }
    }
  }

2.修改 store/index.js 中的 state

const state = sessionStorage.getItem('state') ? JSON.parse(sessionStorage.getItem('state')) : {
  user: {
    name: ''
  }
};
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值