VUE

VUE

(官网:https://cn.vuejs.org/)

常用属性:

  • v-if
  • v-else
  • v-else-if
  • v-for
  • v-on:绑定事件 简写@
  • v-model:数据双向绑定
  • v-bind:给组件绑定参数,简写:

组件化:

  • 组合组件slot插槽
  • 组件内部绑定事件需要使用到this.$emit("事件名",参数)
  • 计算属性的特色,缓存计算数据

vue绑定事件

image-20201125094558359

vue双向绑定

image-20201125100242200

image-20201125100304400

vue组件

image-20201125091947892

网络通信

Axios:实现AJAX异步通信

image-20201125105111975

计算属性

计算出来的结果保存在属性中,将不经常变化的计算结果进行缓存,节约系统开销

image-20201125110844301

插槽slot

image-20201130100055991

自定义事件分发

image-20201214110320052

image-20201214105451741

webpack

安装webpack:npm install webpack -g,npm install webpack-cli -g

1.定义一个hello.js,并暴露它的方法

//暴露一个方法
exports.sayHi=function () {
    document.write("<h1>狂神说ES6</h1>")
}

2.定义main.js,并导入js

var hello=require("./hello");
hello.sayHi();

3.建立webpack.config.js,编写配置

module.exports={
    entry:'./modules/main.js',			//入口
    output:{							//输出
        filename:"./js/bundle.js"
    }
}

4.命令行运行webpack或者webpack --watch(热部署)

image-20201218150750983

5.编写index.xml,并引入生成的bundle.js文件

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    	<script src="dist/js/bundle.js"></script>
    </body>
</html>

6.打开浏览器测试

image-20201218151036925

vue-router

1.在项目下安装vue-router:npm install vue-router --save-dev

2.新建一个router文件夹,并编写路由文件index.js

import Vue from 'vue';
import VueRouter from "vue-router";
import Content from "../components/Content";
import Main from "../components/Main";
//安装路由
Vue.use(VueRouter);

//配置导出路由
export default new VueRouter({
  routes:[
    {//第一个路径
      path:"/content",			//路由路径
      name:'content',			
      component: Content		//跳转组件
    },
    {//第二个路径
      path:"/main",				//路由路径
      name:'main',
      component: Main			//跳转组件
    }
  ]
})

3.在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/>'
});

4.在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>

5.运行npm run dev 测试

image-20201218160335344

vue+Element-ui

(element-ui官网:https://element.eleme.cn/2.0/#/zh-CN)

(layui官网:https://www.layui.com/doc/element/anim.html)

1.新建项目

  • 命令行:vue init webpack hello-vue,等待下载,一路回车,y/n选n,最后一个选最底下的
  • 进入目录:cd hello-vue
  • 安装vue-router:npm install vue-router --save-dev
  • 安装element-ui:npm install element-ui -S
  • 安装依赖:npm install
  • 安装SASS加载器:npm install sass-loader node-sass --save-dev
  • 启动测试:npm run dev

2.IDEA open项目

3.删除无关文件,并创建router文件夹及views文件夹

4.在views文件夹中创建Main.vue及Login.vue文件

Main.vue

<template>
    <h1>首页</h1>
</template>

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

<style scoped>

</style>

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 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.在router文件夹中创建index.js路由文件,并编写路由配置

import Vue from 'vue'
import VueRouter from "vue-router";

import Main from "../views/Main";
import Login from "../views/Login";

Vue.use(VueRouter);

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

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-link to="/login">login</router-link>
      <router-view></router-view>
  </div>
</template>

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

8.npm run dev测试

路由嵌套

1.在需要嵌套的路由里添加路由

import Vue from 'vue'
import VueRouter from "vue-router";

import Main from "../views/Main";
import Login from "../views/Login";
import UserList from "../views/user/List";
import UserProfile from "../views/user/Profile";

Vue.use(VueRouter);

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

2.在Main.vue页面中添加link

<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-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><router-link to="/">退出登录</router-link></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>
  .el-header {
    background-color: #048bd1;
    color: #333;
    line-height: 60px;
  }

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

参数传递及重定向

参数传递方式

第一种{{route.params.id}}

1.携带参数Main.vue

<el-menu-item index="1-1">
    <router-link :to="{name:'/user/profile',params:{id:1}}">个人信息</router-link>
</el-menu-item>

2.修改路由配置index.js

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

3.接收显示参数通过{{route.params.id}}

<template>
  <!--所有元素,必须有根节点-->
  <div>
    <h1>个人信息</h1>
    {{$route.params.id}}
  </div>
</template>

第二种props:true

1.携带参数Main.vue

 <el-menu-item index="1-2">
     <router-link :to="{name:'/user/list',params:{id}}">用户列表</router-link>
</el-menu-item>

2.修改路由配置index.js

{
    path: '/user/list/:id',
    component: UserList,
    props:true       			//支持传递参数
}

3.接收显示参数通过组件props

<template>
  <div>
    <h1>用户列表</h1>
    {{id}}
  </div>
</template>

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

<style scoped>

</style>

重定向

1.配置路由

{
    path:'/gohome',
    redirect:'/main'
}

2.设置页面

<el-dropdown-item><router-link to="/gohome">回到首页</router-link></el-dropdown-item>

注意:

image-20201219212319357

image-20201219212252536

404和路由钩子

路由模式:默认hash

修改路由配置如下:

export default new VueRouter({
  mode:'history',
  routes: [
     
  ]
});

404页面配置

1.编写NotFound.vue页面

<template>
    <div>
      <h1>404,你的页面走丢了!</h1>
    </div>
</template>

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

<style scoped>

</style>

2.配置路由index.js

{
    path:'*',
    name:'404',
    component:NotFound
}

路由钩子

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

参数说明:

  • to:路由要跳转的路径信息,
  • from:跳转前的路径信息,
  • next:路由的控制参数,
    • next():跳入下一个页面;
    • next('/path'):改变路由的跳转方向,使其跳到另一个路由;
    • next(false):返回原来的玉面;
    • next((vm)=>{}):仅在beforeRouterEnter中可用,vm是组件实例

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

(axios官网:http://axios-js.com/)

1.安装axios: npm install --save vue-axios

2.main.js中引用axios

import axios from 'axios'
import VueAxios from 'vue-axios'
Vue.use(VueAxios, axios);

3.使用axios

beforeRouteEnter:(to,from,next)=>{
	console.log("进入路由之前!");//加载数据
	next((vm)=>{
		vm.getData();//进入路由之前执行getData方法
	});
},

4.渲染数据

<template>
  <!--所有元素,必须有根节点-->
  <div>
    <h1>个人信息</h1>
    {{$route.params.id}}
    {{data.name}}
  </div>
</template>

<script>
  export default {
    props:['data'],
    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(response=>this.data=response.data)
      }
    }
  }
</script>

<style scoped>

</style>

image-20201219231751893

posted @ 2020-12-20 17:04  寒离  阅读(88)  评论(0编辑  收藏  举报