vue-router、vue-cli、模块化开发

一、 vue-router

vue-route官方

1. 简介

使用vue.js开发SPA(Single Page Application)单页面应用
根据不同url地址,显示不同的内容,但显示在同一个页面中,称为单页面应用
https://unpkg.com/vue-router/dist/vue-router.js

2. 基本使用

创建单页面应用的几个步骤:
1.定义组件
2.配置路由
3.创建路由实例
4.创建vue实例,并注入路由

    //引入vue.js,vue-router.js
    <style type="text/css">
        .router-link-active{
            color: orange;
            text-decoration: none;
        }
        .active{
            color: orange;
            text-decoration: none;
        }
    </style>
    <div id="app01">
        <div>
            <!-- 使用router-link组件来定义导航,to属性指定链接url -->
            <router-link to="/home">主页</router-link>
            <router-link to="/news">新闻</router-link>
        </div>
        <div>
            <!-- router-view用来显示路由内容 -->
            <router-view></router-view>
        </div>
    </div>
    <script>
        /**
        //1.定义组件
        var Home={
            'template':'<h3>我是主页</h3>'
        };
        var News={
            'template':'<h3>我是新闻</h3>'
        };
        //2.配置路由
        const routes=[
            {path:'/home',component:Home},
            {path:'/news',component:News},
            {path:'/',redirect:'/news'}     //设置默认访问,重定向到news
        ];
        //3.创建路由实例
        const router=new VueRouter({
            routes, //简写    相当于routes:routes
            // mode:'history'   //更改模式,默认hash
            linkActiveClass:'active'    //用于更改活动链接的类名,默认是:router-link-exact-active router-link-active
            linkExactActiveClass:'exact-active' //用于更改活动链接的类名,默认是:router-link-exact-active router-link-active
        });
        **/
        /**
        //以上三步的简写
        const router=new VueRouter({
            routes:[
                {path:'/home',component:{'template':'<h3>我是主页</h3>'}},
                {path:'/news',component:{'template':'<h3>我是新闻</h3>'}},
                {path:'/',redirect:'/home'}

            ]
        });
        //4.创建vue实例并注入路由
        new Vue({
            el:'#app01',
            router      //相当于router:router的简写       该操作又称注入路由
        });
        **/
        //以上4个步骤简写
        new Vue({
            el:'#app01',
            router:new VueRouter({
                routes:[
                    {path:'/home',component:{'template':'<h3>我是主页</h3>'}},
                    {path:'/news',component:{'template':'<h3>我是新闻</h3>'}},
                    {path:'/',redirect:'/home'}
                ]
            })
        });
    </script>

3. 路由嵌套

    <style type="text/css">
        .router-link-active{
            color: orange;
            text-decoration: none;
        }
        .active{
            color: orange;
            text-decoration: none;
        }
    </style>
    <div id="app01">
        <div>
            <!-- 使用router-link组件来定义导航,to属性指定链接url -->
            <router-link to="/home">主页</router-link>
            <router-link to="/user">用户</router-link>
        </div>
        <div>
            <!-- router-view用来显示路由内容 -->
            <router-view></router-view>
        </div>
    </div>
    <template id="user">
        <div>
            <div>
                <ul>
                    <!-- 默认生成a标签 -->
                    <!-- <li><router-link to="/user/login">用户登录</router-link></li> -->
                    <!-- <li><router-link to="/user/regist">用户注册</router-link></li> -->

                    <!-- 使用tag指定标签 -->
                    <router-link to="/user/login" tag="li">用户登录</router-link>
                    <router-link to="/user/regist" tag="li">用户注册</router-link>
                </ul>               
            </div>
            <div>
                <router-view></router-view>
            </div>
        </div>
    </template>
    <script>
        new Vue({
            el:'#app01',
            router:new VueRouter({
                routes:[
                    {
                        path:'/home',
                        component:{'template':'<h3>我是主页</h3>'}
                    },
                    {
                        path:'/user',
                        component:{'template':'#user'},
                        children:[  //通过children实现路由嵌套
                            {
                                path:'login',
                                component:{
                                    'template':'<h4>用户登录</h4>'
                                }
                            },
                            {
                                path:'regist',
                                component:{
                                    'template':'<h4>用户注册</h4>'
                                }
                            }
                        ]
                    },
                    {path:'/',redirect:'/home'}
                ],
            })
        });
    </script>

4. 参数传递

可以获取传递的参数以及url
方式一:普通字符串
方式二:restful方式

    <style type="text/css">
        .router-link-active{
            color: orange;
            text-decoration: none;
        }
        .active{
            color: orange;
            text-decoration: none;
        }
    </style>
    <div id="app01">
        <div>
            <!-- 使用router-link组件来定义导航,to属性指定链接url -->
            <router-link to="/home">主页</router-link>
            <router-link to="/user">用户</router-link>
        </div>
        <div>
            <!-- router-view用来显示路由内容 -->
            <router-view></router-view>
        </div>
    </div>
    <template id="user">
        <div>
            <div>
                <ul>
                    <router-link to="/user/login?username='xhx'&password='123456'" tag="li">用户登录</router-link>
                    <router-link to="/user/regist/alice/123456" tag="li">用户注册</router-link>
                </ul>               
            </div>
            <div>
                <router-view></router-view>
            </div>
        </div>
    </template>
    <script>
        new Vue({
            el:'#app01',
            router:new VueRouter({
                routes:[
                    {
                        path:'/home',
                        component:{'template':'<h3>我是主页</h3>'}
                    },
                    {
                        path:'/user',
                        component:{'template':'#user'},
                        children:[  //通过children实现路由嵌套
                            {
                                path:'login',
                                component:{
                                    'template':'<h4>用户登录    获取参数:{{$route.query}}</h4>'	//普通字符串方式获取参数通过{{$route.query}}获取
                                }
                            },
                            {
                                // path:'regist',
                                path:'regist/:username/:password',      //restful方式获取参数时需要这样配置以区分子路由和参数
                                component:{
                                    //restful方式获取参数通过{{$route.params}}获取,通过{{$route.path}}获取url
                                    'template':'<h4>用户注册    获取参数:{{$route.params}},{{$route.params.username}},{{$route.path}},</h4>'     
                                }
                            }
                        ]
                    },
                    {path:'/',redirect:'/home'}
                ],
            })
        });
    </script>   

5.路由实例的方法

  • router.push() 切换路由
    router.push({path:’/user/login’})
  • router.replace() 替换路由,不产生历史记录
    router.replace({path:’/user/login’})

6.路由动画结合

引入animated.css,使用

    <div id="app01">
        <div>
            <!-- 使用router-link组件来定义导航,to属性指定链接url -->
            <router-link to="/home">主页</router-link>
            <router-link to="/user">用户</router-link>
        </div>
        <div>       
            <transition enter-active-class='animated bounceInLeft' leave-active-class="animated bounceOuterRight">
                <!-- router-view用来显示路由内容 -->
                <router-view></router-view>
            </transition>
        </div>
    </div>

二、单文件组件

1. .vue文件

.vue文件,称为单文件组件,是Vue.js自定义的一种文件格式,一个.vue文件就是一个单独的组件,在组件内封装了相关的代码:html、css、js

.vue文件由三部分组成:、

2. vue-loader

浏览器本身并不认识.vue文件,所以必须对.vue文件进行加载解析,此时需要vue-loader
类似的loader还有许多,如:html-loader、css-loader、style-loader、babel-loader等

需要注意的是vue-loader是基于webpack的

3. webpack

webpack是一个前端资源模块化加载器和打包工具,他能够把各种资源都作为模块来使用和处理
实际上,webpack也是通过不同的loader将这些不同的资源加载后打包,然后输出打包后文件

简单来说:webpack就是一个模块加载器,所有资源都可以作为模块来加载,最好打包输出
官网

webpack版本: v1.x v2.x
webpack有一个核心配置文件:webpack.config.js,必须放在项目根目录下

4. 示例,步骤

4.1 创建项目,目录结构如下:

webpack-demo
|-index.html
|-main.js 入口文件
|-App.vue vue文件
|-package.json 工程文件(创建方式:进入项目目录cmd,npm init –yes)
|-webpack.config.js webpack配置文件
|-.babelrc Babel配置文件

4.2 编写App.vue

<template>
    <div id="itany">
        <h3>welcome to vue</h3>
    </div>
</template>

<script>
    // console.log(111)
</script>

<style>
    body{
        background-color: grey;
    }
</style>

4.3 安装相关关联

cnpm install vue -S

cnpm install webpack -D
cnpm install webpack-dev-server -D

cnpm install vue-loader -D
cnpm install vue-html-loader -D
cnpm install css-loader -D
cnpm install vue-style-loader -D
cnpm install file-loader -D

cnpm install babel-loader -D
cnpm install babel-core -D
cnpm install babel-preset-env -D    //根据配置的运行环境自动启用需要的babel插件
cnpm install vue-template-compiler -D   //预编译模板

合并:cnpm install webpack webpack-dev-server vue-loader vue-html-loader css-loader vue-style-loader file-loader babel-loader babel-core babel-preset-env vue-template-compiler -D

4.4 编写main.js(入口文件)

/**
使用ES6语法引入模板
**/
import Vue from 'vue'
import App from './App.vue'

new Vue({
    el:'#app',
    render:function(h){     //使用render函数渲染组件
        return h(App);
    }
});

4.5 编写webpack.config.js

module.exports={
    //配置入口文件
    entry:'./main.js',
    //配置入口文件输出位置
    output:{
        path:__dirname,     //项目的根路径
        filename:'build.js'     //输出文件名可以自定义,一般用build.js
    },
    //配置模块加载器
    module:{
        rules:[
            {
                test:/\.vue$/, //匹配所有已.vue为结尾的文件都由vue-loader加载
                loader:'vue-loader'
            },
            {
                test:/\.js$/,      //所有以.vue为结尾的文件都由babel-loader加载,除了node-module目录以外
                loader:'babel-loader',
                exclude:/node-modules/
            }
        ]
    }
}

4.6 编写index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
    <div id="app"></div>
    <!-- 需要引入js,js文件名称为4.5中的配置的filename -->
    <script src="build.js"></script>
</body>
</html>

4.7 编写.babelrc文件

{
    "presets":[
        ["env",{"module":false}]
    ]
}

4.8 编写package.json

  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  调整为
  "scripts": {
    "dev": "webpack-dev-server --open --hot"
  },

4.9 运行测试

npm run dev

4.10 多组件开发

一般在当前目录下创建components目录,如果组件非常多可以在components目录下再建目录细分

创建User.vue

<template>
    <div class="user">
        <h3>用户列表</h3>
        <ul>
            <li v-for="value in users">{{value}}</li>
        </ul>
    </div>
</template>

<script>
    export default {
        data(){
            return {
                users:['xhx','zyy','xzt']
            }
        },
    }
</script>

<style scoped>  /*scoped表示样式只在当前组件中生效,防止组件间样式冲突*/
    h3{
        color: red;
    }
</style>

引入到App.vue

<template>
    <div id="itany">
        <h3>welcome to vue</h3>
        <h4 @click="change">{{name}}</h4>
        <!-- <user-list></user-list> -->
        <User></User>
    </div>
</template>

<script>
    //导入模块
    import User from './components/User.vue'

    // console.log(111)
    export default{
        data(){
            return {
                name:'Tom'
            }
        },
        methods:{
            change(){
                this.name='汤姆';
            }
        },
        components:{
            //'user-list':User, //现在模块开发组件命名一般都不修改名字User:User,简写成User
            User,
        }
    }
</script>

<style>
    body{
        background-color: grey;
    }
</style>

4.12 注意事项(样式的作用域)

样式在全局范围生效
样式只在当前.vue文件(也就是当前组件)内生效

三、 vue-cli脚手架

1. 简介

vue-cli是一个vue脚手架,可以快速构建项目结构
vue-cli本身集成了多种项目模板
simple 东西很少,简单
webpack 包含ESLint代码规范检查和unit单元测试等
webpack-simple 没有代码规范检查和单元测试
browserify 使用的也比较多
browserify-simple

2. 实例,步骤:

2.1 安装vue-cli,配置vue命令环境

npm install vue-cli -g
vue –version
vue list

2.2 初始化项目,生成项目目标

语法:vue init 模板名称 项目名
vue init webpack-simple vue-cli-demo

2.3进入生成的项目目录,安装模块包

cd vue-cli-demo
npm install

2.4 运行

npm run dev //启动测试服务
npm run build //将项目打包输出dist目录,项目上线的话需将dist目录拷贝到服务器上

3. 使用webpack模板

vue init webpack vue-cli-demo2
和webpack-simple有点区别,最大差异在于多了ESLint

ESLint是用来统一代码规范和风格的工具,如缩进、空格、符号等,要求比较严格
官网

四、模块化开发

vue init webpack-simple vue-cli-demo

1. vue-router模块化

npm install vue-router -S

1.1 编辑main.js

import Vue from 'vue'
//1.引入vue-router
import VueRouter from 'vue-router'
import App from './App.vue'
//3.引入路由配置(由于路由比较多我们一般都会建一个单独的路由配置文件)
import routerConfig from './router.config.js'

//2.使用vue-router
Vue.use(VueRouter);

//4.创建路由实例
const router = new VueRouter(routerConfig)

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

1.2 编辑App.vue

<template>
  <div id="app">
    {{msg}}
    <h3>
      <router-link to="/home">主页</router-link>
      <router-link to="/news">新闻</router-link>
    </h3>
    <div>
      <keep-alive>
        <router-view></router-view>
      </keep-alive>
    </div>
  </div>
</template>

<script>
export default {
  name: 'app',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  mounted(){
    console.log(this.$route);
  },
  watch:{
    $route:function(newValue,oldValue){
      console.log('路由发送变化,跳转到'+newValue.path);
    }
  }
}
</script>
</script>

1.3 编辑router.config.js

import Home from './components/Home.vue'
import News from './components/News.vue'

export default {
    routes:[
        {
            path:'/home',
            component:Home
        },
        {
            path:'/news',
            component:News
        }
    ]
}

2. axios模块化

npm install axios -S

使用axios的俩种方式:
方式一:在每一个组件中引入axios
import axios from ‘axios’

//比如App.vue中使用axios
<template>
  <div id="app">
    {{msg}}
    <h3>
      <router-link to="/home">主页</router-link>
      <router-link to="/news">新闻</router-link>
    </h3>
    <div>
      <keep-alive>
        <router-view></router-view>
      </keep-alive>
    </div>
    <br>
    <button @click="send">发送ajax请求</button>
  </div>
</template>

<script>
import axios from 'axios'
export default {
  name: 'app',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  mounted(){
    console.log(this.$route);
  },
  watch:{
    $route:function(newValue,oldValue){
      console.log('路由发送变化,跳转到'+newValue.path);
    }
  },
  methods:{
    send(){
      axios.get('https://api.github.com/users/xuhaixiangxhx')
        .then(resp => {
          console.log(resp.data);
        }).catch(err => {
          console.log(err);
        });
    }
  }
}
</script>
方式二:在main.js中进行全局引入,并添加到vue的原型中
        import axios from 'axios'
        Vue.prototype.$http=axios
//main.js
import Vue from 'vue'
//引入vue-router
import VueRouter from 'vue-router'
import App from './App.vue'
//引入路由配置
import routerConfig from './router.config.js'

import axios from 'axios'   //1.全局引入axios

//使用vue-router
Vue.use(VueRouter);

Vue.prototype.$http = axios;	//2.全局引入axios,$http也可以定义成axios等其它自定义名字

//创建路由实例
const router = new VueRouter(routerConfig)

new Vue({
  el: '#app',
  render: h => h(App),
  router
})
//App.vue
<template>
  <div id="app">
    {{msg}}
    <h3>
      <router-link to="/home">主页</router-link>
      <router-link to="/news">新闻</router-link>
    </h3>
    <div>
      <keep-alive>
        <router-view></router-view>
      </keep-alive>
    </div>
    <br>
    <button @click="send">发送ajax请求</button>
  </div>
</template>

<script>
export default {
  name: 'app',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  mounted(){
    console.log(this.$route);
  },
  watch:{
    $route:function(newValue,oldValue){
      console.log('路由发送变化,跳转到'+newValue.path);
    }
  },
  methods:{
    send(){
      this.$http.get('https://api.github.com/users/xuhaixiangxhx')
        .then(resp => {
          console.log(resp.data);
        }).catch(err => {
          console.log(err);
        });
    }
  }
}
</script>

3. 为自定义组件添加事件

components目录下创建自定义组件MyButton.vue

//MyButton.vue组件

<template>
    <div id="my-button">
        <button>自定义按钮发送ajax请求</button>
    </div>
</template>

<style scoped>
    button{
        height: 30px;
        width: 200px;
        color: red;
        border-radius: 5px;
    }
</style>

APP.vue中引入button(import MyButton from ‘./components/MyButton.vue’);
并注册到组件
components:{ //2.注册组件
MyButton
}
APP.vue中template中添加

//APP.vue组件

<template>
  <div id="app">
    {{msg}}
    <h3>
      <router-link to="/home">主页</router-link>
      <router-link to="/news">新闻</router-link>
    </h3>
    <div>
      <keep-alive>
        <router-view></router-view>
      </keep-alive>
    </div>
    <br>
    <button @click="send">发送ajax请求</button>
    <!-- 自定义组件添加事件需要加native修饰符 -->
    <!-- <MyButton @click="send"></MyButton> -->
    <MyButton @click.native="send"></MyButton>      //3.自定义组件绑定事件
  </div>
</template>

<script>
// import axios from 'axios'
import MyButton from './components/MyButton.vue'  //1.引入button
export default {
  name: 'app',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  },
  mounted(){
    console.log(this.$route);
  },
  watch:{
    $route:function(newValue,oldValue){
      console.log('路由发送变化,跳转到'+newValue.path);
    }
  },
  methods:{
    send(){
      this.$http.get('https://api.github.com/users/xuhaixiangxhx')
        .then(resp => {
          console.log(resp.data);
        }).catch(err => {
          console.log(err);
        });
    }
  },
  components:{    //2.注册组件
    MyButton
  }
}
</script>

猜你喜欢

转载自blog.csdn.net/qq_16688265/article/details/79843479
今日推荐