Vue学习

Vue

Vue官网

Soc关注点分离原则
HTML+CSS+JS : 给用户看,刷新后台给的数据
CSS预处理器:专门的编程语言,进行web页面样式设计,通过编译器转化为正常的CSS文件,以供项目使用,主要有:

  1. SASS:基于Ruby语言,难度高于LESS
  2. LESS:基于NodeJS,功能比SASS简单,效率较低,后台开发建议使用LESS

网络通信:axios(现在Vue不包网络通信,现在主要是用这个处理,即前端通信框架)
页面跳转:vue-router
状态管理:vuex
vue-UI:ICE(阿里巴巴的,自行百度)

UI框架:

  1. Ant-Design:阿里巴巴出品,基于react的UI框架
  2. Element、iview、ice:饿了么chup,基于vue的UI框架
  3. Bootstrap:推特推出,前端开发开源工具包
  4. AmazeUI:HTML5跨屏前端框架

JavaScript构建工具:
5. Babel
6.WebPack:打包前端

Vue开发工具:
6. Vscode
7. Hbuilder
8. Sublime
9. WebStrom
但是直接用idea就可以了,因为足够万能


第一个vue程序

1. 直接在目录里创建一个vue文件,再用idea打开 ,like this:

在这里插入图片描述

2. 安装vue.js的插件

在这里插入图片描述

3. Vue.js用cdn方式引入

自行百度vue.js cdn查找版本

 <script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>

4.使用html文件写一个vue项目

(vue-first/chapter-1/demo1.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<!--view层 模板-->
<div id="app">
    <h1>{{message}}</h1>
    
    <!--使用v-bind绑定元素-->
    <span v-bind:title="message2">
        鼠标悬停几秒可以查看此处动态绑定的提示信息
    </span>
</div>



<!--1.导入Vue.js-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.js"></script>
<script>
    let vm = new Vue({
        el:"#app",   //元素绑定id
        //Model,数据层
        data:{      //数据,前后端分离,是对象,键值对
            message:"hello,Vue!",
            message2:"这里是v-bind显示"
        }
    })
</script>

</body>
</html>
  1. Vue只要主要实现了前后端分离的功能,即视图不影响数据,数据不影响视图,按照上诉的代码写好在网页中渲染后,已经和DOM建立了练习,可以直接在console里面修改测试数据,实时更新:
    在这里插入图片描述
    即写网页时不用再依赖从后台数据库中获取数据再显示到前端,写好网页后,后台直接在Vue对象中改就可以了
  2. 关于 v-bind
    v-bind被称为指令,带有前缀v-,表示它是Vue提供的特殊特性,这里的意思是通过标签绑定Vue对象中的message2属性,不用使用{{message2}}。
    显示效果:
    在这里插入图片描述
    并且在控制台也可以直接动态修改它的值

5.语法v-if、v-elseif、v-else

(vue-first/chapter-1/demo2.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div id="app">
    <h1 v-if="ok">YES</h1>
    <h1 v-else>NO</h1>

    <h1 v-if="type==='A'">A</h1>
    <h1 v-else-if="type==='B'">B</h1>
    <h1 v-else>C</h1>
</div>


<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.js"></script>
<script>
    let vm = new Vue({
        el:"#app",
        data:{
            ok: true,
            type:'B'
        }
    })
</script>

</body>
</html>

6. 语法for

(vue-first/chapter-1/demo3.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div id="app">
   <li v-for="item in items">
       {{item.message}}
   </li>
---------------------------------------------
    <li v-for="(item, index) in items">
        {{item.message}}--{{index}}
    </li>

</div>


<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.js"></script>
<script>
    let vm = new Vue({
        el:"#app",
        data:{
            items:[
                {message: '蒋二妹学Java'},
                {message: '蒋二妹太困了'},
                {message: '蒋二妹困死了'}
            ]
        }
    })
</script>

</body>
</html>

关于绑定

1. 绑定事件

(vue-first/chapter-1/demo4.html)

v-on可以绑定很多事件,如果记不住的话,百度JQuery文档查看各种事件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div id="app">
    <!--v-on绑定事件并添加Vue中的方法,忘记事件就搜JQuery文档-->
    <button v-on:click="sayHi">Click Me !</button>
</div>


<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.js"></script>
<script>
    let vm = new Vue({
        el:"#app",
        data:{
            message: "二妹学Java"
        },
        methods:{   //方法必须定义在Vue的methods对象中
            sayHi:function (){
                alert(this.message);
            }

        }
    })
</script>

</body>
</html>

2.双向数据绑定

(vue-first/chapter-1/demo5.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div id="app">

    输入的文本:<input type="text" v-model="message"> {{message}}
    <br>
    <br>

    <textarea name="" id="" cols="30" rows="10" v-model="message2"></textarea>{{message2}}
    <br>
    <br>

    性别:
    <input type="radio" name="sex" value="" v-model="sex"><input type="radio" name="sex" value="" v-model="sex"><p>选中了:{{sex}}</p>

    下拉框:
    <select v-model="char">
        <option value="" disabled>--请选择--</option>
        <option>A</option>
        <option>B</option>
        <option>C</option>
    </select>
    <p>选中了:{{char}}</p>

    下拉框(默认有选中):
    <select v-model="char2">
        <option>Aa</option>
        <option>Bb</option>
        <option>Cc</option>
    </select>
    <p>选中了:{{char2}}</p>
</div>


<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.js"></script>
<script>
    let vm = new Vue({
        el:"#app",
        data:{
            message:"",
            message2: "",
            sex:"",
            char:"",
            char2:"Aa"
        }
    })
</script>

</body>
</html>

即实现数据发生变化,视图发生变化;试图发生变化,数据也发生变化
对UI控件来说
使用v-model进行绑定,监听输入时间和及时更新数据


组件

(vue-first/chapter-1/demo6.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div id="app">

   <comp v-for="item in items" v-bind:pro="item"></comp>

</div>


<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.js"></script>
<script>

    //定义一个Vue组件component
    Vue.component("comp",{
        props:['pro'],  //接收参数
        template:'<li>{{pro}}</li>'
    })

    let vm = new Vue({
        el:"#app",
        data:{
            items:["java","Web","Vue"]
        }
    })
</script>

</body>
</html>
  • 可复用的Vue实例,也就是使用Vue.component(名字,{对象{}),就可以在网页中直接用名字当标签复用,减少冗余。
  • 如上代码,script中的Vue是同级的,所以上面的组件不能直接获取到下面定义到的数据,即:要通过中间商,先用v-for循环出来,在用v-bind绑定一个随意的变量后,在组件中用props接收数据,然后就可以放在组件相应的位置啦

网络通信Axios

Axios中文官网

引入:1. 下载导入包 2. CDN

Axios是一个开源的可以在浏览器和|NodeJS的异步通信框架,实现Axios异步通信

后续在vue-cli中: npm install axios

创建一个data.json

{
  "name": "钱锟",
  "url": "https://baike.baidu.com/item/%E9%92%B1%E9%94%9F/10634721?fr=aladdin",
  "page": 1,
  "isNonProfit": true,
  "address": {
    "street": "花路",
    "city": "三明市",
    "country":"福建省"
  },
  "links": [
    {
      "name":"百度",
      "url":"https://www.baidu.com/"
    },
    {
      "name":"知乎",
      "url":"https://www.zhihu.com/"
    },
    {
      "name": "QQ",
      "url":"https://im.qq.com/"
    }
  ]
}

异步获取JSON数据

(vue-first/chapter-1/demo7.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <!--v-cloak:解决闪烁问题-->
    <style>
        [v-cloak]{
            display: none;
        }
    </style>

</head>
<body>

<div id="vue" v-cloak>
    <div>{{info.name}}</div>
    <div>{{info.address.street}}</div>

    <a v-bind:href="info.url">钱锟百度百科</a>
</div>



<!--引入js文件-->
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.js"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script type="text/javascript">
    let vm = new Vue({
        el:'#vue',
        //data:{}  这里的data是属性,但是要接收下面的数据,用的必须是data()方法,再return接收
        data(){
            return{
                //请求的返回参数,必须和JSON的字符串一样
                info:{
                    name:null,
                    address:{
                        street:null,
                        city:null,
                        country:null,
                    },
                    url:null
                }
            }
        },
        mounted(){    //钩子函数  连式编程  ES6新特性
            //在控制台输出从data.json中获取的数据,在Network中查看异步显示
            //axios.get('../data.json').then(response=>(console.log(response.data)));
            axios.get('../data.json').then(response=>(this.info=response.data));

        }
    })
</script>
</body>
</html>

计算属性

(vue-first/chapter-1/demo8.html)

  • 将计算出来的结果保存在属性中----->内存中运行:虚拟DOM
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div id="app">
    <p>方法:currentTime1():{{currentTime1()}}</p>
    <p>属性:currentTime2:{{currentTime2}}</p>
</div>


<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.js"></script>
<script>
    let vm = new Vue({
        el:"#app",
        data:{
            message: "我直接 “嗨,老公!” ",
        },
        methods:{
            currentTime1: function () {
                return Date.now();   //返回一个时间戳
            }
        },
        computed: {    //计算属性:methods和computed中的方法不能重名,重名后只会调用method中的方法
            currentTime2: function () {
                //这个在控制台测试,控制台连续输出currentTime2时间戳都不变,但是在控制台修改了message后就重新计算了,相当于是计算属性搞了一个缓存(将不经常变化的计算结果进行缓存)
                this.message;
                return Date.now();   //返回一个时间戳
            }
        }
    })
</script>

</body>
</html>

插槽 slot

(vue-first/chapter-1/demo9.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div id="app">

   <todo>
       <todo-title slot="todo-title" v-bind:title="title"></todo-title>
       <todo-items slot="todo-items" v-for="itme in todoItems" v-bind:item="itme"></todo-items>
   </todo>

</div>


<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.js"></script>
<script>
    //slot:插槽
    Vue.component("todo",{
        template:
                '<div>\
                     <slot name="todo-title"></slot>\
                     <ul>\
                        <slot name="todo-items"></slot>\
                     </ul>\
                </div>'
    });

    Vue.component("todo-title",{
        props:['title'],
        template:'<div>{{title}}</div>'
    });

    Vue.component("todo-items",{
        props:['item'],
        template: '<li>{{item}}</li>'
    })

    let vm = new Vue({
        el:"#app",
        data:{
            title:"课程",
            todoItems:['Java','Lunix','Python']
        }
    })
</script>

</body>
</html>

关于插槽:
首先定义一个范围大的组件模板,就是在这个模板里面使用插槽,然后定义插槽对应的应该插入的哪些标签模板,之后在slot标签用name属性绑定对应的后,在视图放入大的组件模板标签,在里面放入插槽对应的模板标签,用slot属性绑定,最后再进行数据绑定传输


自定义事件

(vue-first/chapter-1/demo9.html)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div id="app">

   <todo>
       <todo-title slot="todo-title" v-bind:title="title"></todo-title>
       <todo-items slot="todo-items" v-for="(item,index) in todoItems" v-bind:item="item" v-bind:index="index" v-on:remove="removeItems(index)"></todo-items>
   </todo>

</div>


<script src="https://cdn.jsdelivr.net/npm/vue@2.5.21/dist/vue.js"></script>
<script>
    //slot:插槽
    Vue.component("todo",{
        template:
                '<div>\
                     <slot name="todo-title"></slot>\
                     <ul>\
                        <slot name="todo-items"></slot>\
                     </ul>\
                </div>'
    });

    Vue.component("todo-title",{
        props:['title'],
        template:'<div>{{title}}</div>'
    });

    Vue.component("todo-items",{
        props:['item','index'],
        //只能绑定当前组件的方法
        template: '<li>{{index}}---{{item}} <button @click="remove">删除</button></li>',
        methods:{
            remove:function(index){
                //this.$emit自定义事件
                this.$emit('remove',index)
            }
        }
    })

    let vm = new Vue({
        el:"#app",
        data:{
            title:"课程",
            todoItems:['Java','Lunix','Python']
        },
        methods: {
          removeItems:function (index){
              console.log("删除了"+this.todoItems[index]+"OK");
              this.todoItems.splice(index,1)
          }
        }
    })
</script>

</body>
</html>

关于自定义事件

  • 由于在组件里面定义的方法只能绑定当前组件
    在这里插入图片描述
    在这里插入图片描述

  • 如果要控制组件改变Vue对象的数据或者别的,也就是对Vue对象进行操作
    在Vue对象中创建方法后,在视图层用v-on自定义命名绑定后,在组件中的方法中使用this.$emit()绑定匹配

    在这里插入图片描述
    在这里插入图片描述



到这里Vue基础就结束了



第一个Vue-Cli项目

在这里插入图片描述

环境搭建:

安装Node.JS

Node.JS下载地址

  1. 下载后安装在自己的环境目录,无脑下一步(node自动配置环境变量)
  2. cmd测试安装是否成功
#cmd下输入node -v,查看是否能打印出正确的版本号
node -v
#cmd下输入npm -v,查看是否能打印出正确的版本号
#npm就是自带的软件包管理工具
npm -v
  1. 安装淘宝镜像加速器(cnpm)
    虽然安装了cnpm,但是少用(可能会出现一些奇奇怪怪的问题)
#全局安装淘宝镜像
npm install cnpm -g

#或者使用下main语句解决npm速度慢的问题
npm install --registry=https://registry.npm.taobao.org
  • 安好了文件都在这里在这里插入图片描述
  1. 安装vue-cli
cnpm install vue-cli -g 

#也可以用国外镜像下载,好像可以解决npm run dev出现的错误,建议直接使用它
npm install vue-cli -g 
#查看是否安装成功
#查看可以基于哪些模板创建vue应用程序,通常我们选择webpack
vue list

Git

Git下载地址

第一个vue-cli应用程序

1.初始化后用Dos命令运行

  1. 可以新建一个目录文件夹
  2. 管理员模式使用cmd命令行通过命令进入目录文件夹后
#这里的myvue是项目名称,可以根据自己的需求起名
vue init webpack myvue

跳出选项一路选no(因为学习时后面会自己搭建安装,平时可以Yes)

创建成功后可以在项目文件夹的package.json查看具体信息

  1. 初始化运行
cd myvue
npm install      #命令好了以后,myvue中会显示node_modules文件夹,出现警告就按照提示运行
npm run dev      #打包启动,就像tomcat启动关闭一样

如果npm run dev遇到了错误,就在上面安装的时候用国外镜像

成功!!!!!!
在这里插入图片描述

在这里插入图片描述

Ctrl+C 停止运行
注意:用idea要在.exe属性里面设置以管理员身份运行!

2. 直接用idea打开项目后,可以在终端输入 命令执行

idea终端执行运行命令

  • 如果运行不了,就去找idea所在文件夹右键属性以管理员身份运行

  • 项目目录结构:
    在这里插入图片描述
    源码在src
    程序主入口在main.js
    build文件夹包含构建文件

    • webpack.base.config.js —> 打包

    index.html —> 主入口:里面的div id=”app“,绑定的是main.js里面对应的


Webpack

安装Webpack

Webpack是一款模块加载器兼打包工具,它能把各种资源,如JS、JSX、ES6、SASS、LESS、图片

安装:

npm install webpack -g   #打包工具
npm install webpack-cli -g    #客户端

测试安装成功:

  • webpack -v
  • webpack-cli -v

使用webpack

1. 在项目目录创建一个项目

2. 创建一个modules目录,用来存放js文件

3. 创建js文件,实现暴露方法,引入模块

在这里插入图片描述

4. 创建webpack.config.js

module.exports = {
    entry:'./modules/main.js',   //定义程序入口
    output:{
        filename:'./js/bundle.js'
    }
};

5. 在终端输入webpack打包执行

在这里插入图片描述

6. 新建index.html

```html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<!--前端的模块化开发-->
<script src="dist/js/bundle.js"></script>

</body>
</html>
```

7. 运行查看效果即可


vue-route

1. 安装vue-route:

npm install vue-route --sava-dev

2. 在一个模块化工程使用,必须通过Vue.use()明确安装路由功能:

import Vue from 'vue'
import VueRouter from 'vue-route'

//安装路由
Vue.use(VueRouter);

3. 删除无关的文件,在components中创建自己需要用到的组件

4. 在src文件夹中新建文件夹router,专门存放路由

import Vue from 'vue'
//导入路由插件
import Router from 'vue-route'
//导入上面定义的组件
import Content from "../components/Content";
import main from "../components/main";

//安装路由
Vue.use(Router);


//配置导出路由
export default new Router({
  routes:[
    {
    //路由路径
    path: '/content',
    name: 'Content',
    //路由的组件
    component: Content
  },
  {
    //路由路径
    path: '/main',
    name: 'main',
    //路由的组件
    component: main
  }
  ]
})

5. 在main.js中配置路由

import Vue from 'vue'
import App from './App'
//导入之前创建的路由配置目录
import router from './router'    //自动扫描里面的路由配置

//来关闭生产模式下的提示
Vue.config.productionTip = false


new Vue({
  el: '#app',
  //配置路由
  router,
  components: { App },
  template: '<App/>'
})

6. 在App.vue中使用路由

<template>
  <div id="app">

    <h1>Vue-Router</h1>
    <router-link to="/main">首页</router-link>
    <router-link to="/content">内容页</router-link>
    <router-view></router-view>

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

到这里会跳啥啥is not a function,没解决,解决不了


ElementUI

ElementUI中文文档

1. 创建一个工程

vue init webpack hello-vue

2. 安装依赖,即vue-router、element-ui、sass-loader、node-sass四个插件

#进入工程项目
cd hello-vue
#安装vue-router
npm install vue-router --save-dev
#安装element-ui
npm i element-ui -S
#安装依赖
npm install
#安装SASS加载器
cnpm install sass-loader node-sass --sava-dev
#启动测试
npm run dev

3. 用idea打开项目,删掉多余的内容,创建自己需要的文件

创建router、views文件夹

注:views存放视图组件,components存放功能组件

4. 创建登录界面,在views中创建一个Login.vue的视图组件

<template>
  <div>
    <el-form ref="loginForm" :model="form" :rules="rules" label-width="80px" class="login-box">
      <h3 class="login-title">欢迎登录</h3>
      <el-form-item label="账号" prop="username">
        <el-input type="text" placeholder="请输入账号" v-model="form.username"/>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" placeholder="请输入密码" v-model="form.password"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" v-on:click="onSubmit('loginForm')">登录</el-button>
      </el-form-item>
    </el-form>

    <el-dialog
      title="温馨提示"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose">
      <span>请输入账号和密码</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name:"Login",
    data(){
      return {
        form:{
          username: '',
          password: ''
        },
        //表单验证,需要再el-form-item 元素中增加prop属性
        rules:{
          username:[
            {required:true,message:'账号不能为空',trigger:'blur'}
          ],
          password:[
            {required: true,message: '密码不能为空',trigger:'blur'}
          ]
        },
        //对话框显示和隐藏
        dialogVisible:false
      }
    },
    methods:{
      onSubmit(formName) {
        //为表单绑定验证功能
        this.$refs[formName].validate((valid) =>{
          if (valid){
            //使用 vue-router路由到指定页面,该方式称之为编程式导航
            this.$router.push("/main");
          } else {
            this.dialogVisible = true;
            return false;
          }
        });
      }
    }
  }
</script>


<style lang="scss" scoped>
.login-box{
  border: 1px solid #DCDFE6;
  width: 350px;
  margin:180px auto;
  padding:35px 35px 15px 35px;
  border-radius: 5px;
  -webkit-border-radius: 5px;
  -moz-border-radius: 5px;
  box-shadow:0 0 25px #909399;
}

.login-title{
  text-align:center;
  margin:0 auto 40px auto;
  color:#303133;
}
</style>

5. 创建了视图组件就可以配置路由了

import Vue from 'vue'
import Router from 'vue-router'
import Main from "../views/Main";
import Login from "../views/Login";
// import HelloWorld from '@/components/HelloWorld'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/main',
      name: 'main',
      component: Main
    },
    {
      path: '/login',
      name: 'login',
      component: Login
    }
  ]
})

6. 将路由配置到main.js里面

import Vue from 'vue'
import App from './App'
import router from './router'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';

Vue.use(router);
Vue.use(ElementUI);



new Vue({
  el: '#app',
  router,
  render: h => h(App)   //ElementUI
})

7. 修改App.vue

<template>
  <div id="app">

    <router-view></router-view>

  </div>
</template>

<script>
export default {
  name: 'App'
}
</script>

排错this.getOptions is not a function

以上代码写好后,出现错误Module build failed: TypeError: this.getOptions is not a function

原因:sass-loader版本太高,在package.json中修改版本为"sass-loader": "^7.3.1",由于修改了版本,所以需要重新在控制台输入命令npm install

排错Cannot find module ‘node-sass’

上面排错后还是跳错误:Module build failed: Error: Cannot find module 'node-sass'

原因:可能是因为npm install并没有完全下载下来,使用cnpm install试试
结果还是报错,重新安装node sass,执行npm install node-sass --save-dev,发现提示说版本太高,就修改版本为4.0.0,再重新安装,终于绿了

  1. 进入登录界面
    由于一开始进到界面是空白的,所以在后面添加即可
    http://localhost:8080/#/login
    在这里插入图片描述

嵌套路由

1. 在views中创建一个user文件夹,然后再创建Profile、List组件

  1. Profile.vue

    <template>
      <h1>个人信息</h1>
    </template>
    
    <script>
    export default {
      name: "UserProfile"
    }
    </script>
    
    <style scoped>
    
    </style>
    
    

    2.List.vue

    <template>
      <h1>用户列表</h1>
    </template>
    
    <script>
    export default {
      name: "UserList"
    }
    </script>
    
    <style scoped>
    
    </style>
    
    

2. 在Main.vue中添加内容

<template>
  <div>
    <el-container>
      <el-aside width="200px">
        <el-menu :default-openeds="['1']">

          <el-submenu index="1">
            <template slot="title"><i class="el-icon-caret-right"></i>用户管理</template>
            <el-menu-item-group>
              <el-menu-item index="1-1">
                <router-link to="/user/profile">个人信息</router-link>
              </el-menu-item>
              <el-menu-item index="1-2">
                <router-link to="/user/list">用户列表</router-link>
              </el-menu-item>
            </el-menu-item-group>
          </el-submenu>

          <el-submenu index="2">
            <template slot="title"><i class="el-icon-caret-right"></i>内容管理</template>
            <el-menu-item-group>
              <el-menu-item index="2-1">分类管理</el-menu-item>
              <el-menu-item index="2-2">内容列表</el-menu-item>
            </el-menu-item-group>
          </el-submenu>

          <el-submenu index="3">
            <template slot="title"><i class="el-icon-caret-right"></i>系统设置</template>
            <el-menu-item-group>
              <el-menu-item index="3-1">用户设置</el-menu-item>
            </el-menu-item-group>
          </el-submenu>

        </el-menu>
      </el-aside>

      <el-container>
        <el-header style="text-align: right; font-size: 12px">
          <el-dropdown>
            <i class="el-icon-setting" style="margin-right:15px"></i>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item>个人信息</el-dropdown-item>
              <el-dropdown-item>退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </el-header>

        <el-main>
          <router-view/>
        </el-main>

      </el-container>
    </el-container>
  </div>
</template>

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

<style scoped lang="scss">
.el-header {
  background-color: #1f8ac2;
  color: #333;
  line-height: 60px;
}

.el-aside {
  color: #333;
}
</style>

3. 定义了组件就要把它们定义到路由中去

import Vue from 'vue'
import Router from 'vue-router'
import Main from "../views/Main";
import Login from "../views/Login";

import UserProfile from "../views/user/Profile";
import UserList from "../views/user/List";
// import HelloWorld from '@/components/HelloWorld'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/main',
      name: 'main',
      component: Main,
      //嵌套路由
      children: [
        {path: '/user/profile',component: UserProfile},
        {path: '/user/list',component: UserList}
      ]
    },
    {
      path: '/login',
      name: 'login',
      component: Login
    }
  ]
})

子路由,嵌套


传递参数及重定向

传递参数

1. 使用router-link传递参数,定义参数名和参数值

 <!--name-传组件名;params-传递参数;需要对象:v-bind:-->
 <router-link :to="{name: 'UserProfile',params:{id: 1}}">个人信息</router-link>

2. 在路由配置里面对应的添加参数名

{path: '/user/profile/:id',name:'UserProfile', component: UserProfile}

再添加个参数就是/:参数名

3. 显示参数界面添加

<template>
  <div>
    <h1>个人信息</h1>
    {{$route.params.id }}
  </div>
</template>

注:所有的元素,不能直接在根节点<template>

通过props解耦

1. 在相应的路由配置中添加

 {path: '/user/profile/:id',name:'UserProfile', component: UserProfile, props:true}

2. router-link不用变

3. 显示参数界面

<template>
  <div>
    <h1>个人信息</h1>
    {{id}}
  </div>
</template>

<script>
export default {
  props:['id'],
  name: "UserProfile"
}
</script>

重定向

1. 在路由配置中添加

{
	path: '/goHome',
	redirect: '/main'   //重定向的目标
}

2. router-link配置

<el-menu-item index="1-3">
	<router-link to="/goHome">回到首页</router-link>
</el-menu-item>

钩子

	 beforeRouteEnter:(to, from, next)=>{
        console.log("进入路由之前");
        next();
      },
      beforeRouteLeave:(to, from, next) =>{
        console.log("进入路由之后");
        next();
      }

在钩子函数中使用Axios异步请求

安装 Axios: cnpm install axios -s

  1. 在路口文件main.js中引入
import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(VueAxios,axios)
  1. 在static中新建文件夹mock(专有名词不能改变),再在后面创建data.json
    数据:
{
  "name": "钱锟",
  "url": "https://baike.baidu.com/item/%E9%92%B1%E9%94%9F/10634721?fr=aladdin",
  "page": 1,
  "isNonProfit": true,
  "address": {
    "street": "花路",
    "city": "三明市",
    "country":"福建省"
  },
  "links": [
    {
      "name":"百度",
      "url":"https://www.baidu.com/"
    },
    {
      "name":"知乎",
      "url":"https://www.zhihu.com/"
    },
    {
      "name": "QQ",
      "url":"https://im.qq.com/"
    }
  ]
}
  1. 数据展示页面请求数据
<template>
  <div>
    <h1>个人信息</h1>
    {{id}}
  </div>
</template>

<script>
  export default {
      props:['id'],
      name: "UserProfile",
      beforeRouteEnter:(to, from, next)=>{
        console.log("进入路由之前");  //加载数据
        next(vm => {
          vm.getData();  //进入路由之前执行getData()方法
        });
      },
      beforeRouteLeave:(to, from, next) =>{
        console.log("进入路由之后");
        next();
      },
    methods:{
        getData: function (){
          this.axios({
            method:"get",
            url:"http://localhost:8080/static/mock/data.json"
          }).then(function (response){
            console.log(response);
          })

        }
    }
  }
</script>

<style scoped>

</style>

怎么展示数据就按照之前Axios的方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值