vue进阶02-vue入门(helloworld和路由应用)

1.vue简介

Vue (读音 /vjuː/,类似于 view) 是一套用于构建用户界面的渐进式框架。与其它大型框架不同的是,Vue 被设计为可以自底向上逐层应用。Vue 的核心库只关注视图层,不仅易于上手,还便于与第三方库或既有项目整合。另一方面,当与现代化的工具链以及各种支持类库结合使用时,Vue 也完全能够为复杂的单页应用提供驱动。

关于vue语法学习网站(语法就不在教程体现了):

2.vue入门

这里演示不使用脚手架vue-cli方式开发,抬高入门门槛,利于学习原理。

2.1 安装初始环境

安装最新版webpack,各种loader等

cnpm i -D clean-webpack-plugin css-loader extract-text-webpack-plugin@next file-loader html-loader html-webpack-plugin style-loader vue-loader vue-template-compiler webpack webpack-cli webpack-dev-server babel-core babel-loader babel-plugin-transform-runtime babel-preset-es2015

其中 vue-loader vue-template-compiler 是vue相关的
webpack标准配置(webpack.config.js)

//import path from 'path'
path=require("path")
htmlWebpackPlugin=require("html-webpack-plugin")
ExtractTextPlugin=require("extract-text-webpack-plugin")
const VueLoaderPlugin = require('vue-loader/lib/plugin');
Webpack=require("webpack")
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
module.exports={
    // devtool: 'cheap-module-source-map',
    devtool: "source-map",
    //执行webpack 默认的主js文件
    entry: {
        main: "./src/main.js",
    },
    output: {
        //__dirname是当前webpack执行命令的目录
        path: path.join(__dirname,"./dist"),
        //[name]是entry对应文件名称 chunkhash是文件hash值
        //filename: "[name]-[chunkhash].js",
        filename: "[name].js",
    },
    //默认的loader都在node_modules 额外追加./loader目录
    resolveLoader: {
        modules: [path.join(__dirname,"./src/loader"),"node_modules"]
    },
    devServer: {
      contentBase:"./dist"
    },
    module: {
        rules: [
            {
            test:/.css$/,
            use: ExtractTextPlugin.extract({
                fallback: "style-loader", //use出現了錯誤使用fallback對應的loader
                use: "css-loader"
            })
        },
            {
            test:/(.jpg|.png)$/,
            use: {
                loader: "file-loader",
                options: {
                    name: "[name].[hash].[ext]"
                }
            }

        },{
            test: /\.html$/,
            use: [ "html-loader" ]
        },{
                test: /.vue$/,
                use: [
                    'vue-loader'
                ]
            },{
            test: /.txt$/,
            exclude: /node_modules/,
            use:[ {
                loader:"txt-loader",
                options: {
                    resources: {
                        name: "张三"
                    }
                }}]

            }]
    },
    plugins: [
        new CleanWebpackPlugin({
            root:__dirname
        }),
        new htmlWebpackPlugin({
            template:"./src/index.html"
        }),
        new ExtractTextPlugin("styles.css"),
        new Webpack.EnvironmentPlugin(['PATH']),
        new VueLoaderPlugin()
    ]
}

新版本vue需要搭配VueLoaderPlugin一起使用,.vue文件使用vue-loader处理
配置package.json

  "scripts": {
    "build": "webpack",
    "dev": "webpack-dev-server --open"
  },

2.2 vue helloworld

安装vue库

npm i vue vue-router --save

新建src目录,新建index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<body>
  <div id="app">
  </div>
</body>
</html>

其中id=app的div用于渲染生成的vue代码
新建entry chunk main.js

import Vue from 'vue'
import Hello from './Hello.vue'
new Vue({
    el:'#app',//表示生成的代码存放在app这个元素中
    render: h => h(Hello) //从哪个控件中生成代码
})

创建第一个vue类 Hello.vue

<template>
    <div>
        {{msg}}
    </div>
</template>
<script>
  export default {
        data:function () {
            return {
                msg:"helloworld"
            }
        }
  }
</script>
<style>

</style>

vue文件语言块介绍:

  • <template>
    默认语言:html。
    每个 .vue 文件最多包含一个 <template> 块。
    内容将被提取为字符串,将编译并用作 Vue 组件的 template 选项。
  • <script>
    默认语言:js (在检测到 babel-loader 或 buble-loader 配置时自动支持ES2015)。
    每个 .vue 文件最多包含一个 <script> 块。
    该脚本在类 CommonJS 环境中执行 (就像通过 Webpack 打包的正常 js 模块),这意味这你可以 require() 其它依赖。在 ES2015 支持下,你也可以使用 import 和 export 语法。
    脚本必须导出 Vue.js 组件对象。
  • <style>
    默认语言:css。
    一个 .vue 文件可以包含多个 <style> 标签。
    <style> 标签可以有 scoped 或者 module 属性 (查看 CSS 作用域和 CSS Modules) 以帮助你将样式封装到当前组件。具有不同封装模式的多个 <style> 标签可以在同一个组件中混合使用。
    默认情况下,将会使用 style-loader 提取内容,并通过 <style> 标签动态加入文档的 <head> 中,也可以配置 Webpack 将所有 styles 提取到单个 CSS 文件中。

运行

npm run dev

久违的helloworld出现了

2.3 比较data和computed和watch

页面渲染用到的数据

<template>
    <div>
     用户名<input type="text" v-model="userName"/><br/>
        用户性别<input type="text" v-model="userSex"/>
        描述1:{{userDesc1}}
        描述:{{userDesc}}
    </div>


</template>
<script>
  export default {
      data(){
          return {
              userName: "",
              userSex: "",
              userDesc1: this.userName + this.userSex
          }
      },
      computed: {
                  userDesc() {
                     return "您的姓名是:"+this.userName+",您的性别:"+this.userSex
                  }
      },
      watch:{
          userName(newValue,oldValue){
              console.log("userName被修改了"+newValue+",旧值:"+oldValue)
          }
      }
  }
</script>
<style>

</style>
  • computed表示计算属性,不能在data中预先定义,userDesc定义了一个属性(其实是函数),只要关联的username和userSex发生变化userDesc自动发生变化,computed属性不变化时直接读取缓存,发生变化更新缓存,可以直接用 {{userDesc}} 访问当然也可以调用函数 userDesc()。
  • data表示关联属性,userDesc1比如随着username和userSex改变而改变。
  • watch用于监控某个属性是否发生变化,参数1:新值,参数2:旧值。

3.vue进阶

3.1. vue路由

3.1.1路由入门

在vue一般一个应用一个统一的vue入口文件,一般命名为App.vue,所有的代码从这个文件引入。main.js在new Vue时需指定该应用文件:

import Vue from 'vue'
import App from './App.vue'
import router from './router'
new Vue({
    el:'#app',
    router,
    render: h => h(App)
})

render: h => h(App)表示使用./App.vue作为渲染页面的应用文件
新建App.vue,该页面编写首页逻辑:

<template>
    <div id="app">
        <h1>功能列表</h1>
        <ul>
            <li><a href="#/userList">用户列表</a></li>
            <li><a href="#/roleList">角色列表</a></li>
        </ul>
        <router-view></router-view>
    </div>
</template>

其中router-view表示当点击了上面超链接时显示对应链接对应控件的内容

接下来需要定义userList和roleList两个路由。
新建router.js

import Vue from 'vue'
import VueRouter from 'vue-router'
import UserList from './UserList.vue'
import Role from './RoleList.vue'
Vue.use(VueRouter)
// 这里直接默认导出 new 出来的 router 实例
export default new VueRouter({
    routes: [
        {
            path: '/userList',
            component: UserList
        },
        {
            path: '/roleList',
            component: Role
        }
    ]
})

新建UserList.vue

<template>
    <div>
        <table>
            <tr><td>用户id</td><td>用户姓名</td></tr>
            <tr v-for="u in userList"><td>{{u.id}}</td><td>{{u.name}}</td></tr>
        </table>
    </div>
</template>
<script>
  export default {
        data:function () {
            return {
                userList:[
                    {id:1,name:"张三"},
                    {id:2,name:"李四"}
                ]
            }
        }
  }
</script>
<style>

</style>

新建RoleList.vue

<template>
    <div>
        <table>
            <tr><td>角色id</td><td>角色姓名</td></tr>
            <tr v-for="r in roleList"><td>{{r.id}}</td><td>{{r.name}}</td></tr>
        </table>
    </div>
</template>
<script>
  export default {
        data:function () {
            return {
                roleList:[
                    {id:1,name:"管理员"},
                    {id:2,name:"DBA"}
                ]
            }
        }
  }
</script>
<style>

</style>

3.1.2子路由

假设在用户列表页上有个子页面当用户点击张三时 显示用户id:1,点击李四是显示用户id:2

在这里插入图片描述

修改router.js:

import Vue from 'vue'
import VueRouter from 'vue-router'
import UserList from './UserList.vue'
import Role from './RoleList.vue'
import UserDefail from './UserDefail.vue'
Vue.use(VueRouter)
// 这里直接默认导出 new 出来的 router 实例
export default new VueRouter({
    routes: [
        {
            path: '/userList',
            component: UserList,
            children:[{
                path: ':id',
                component: UserDetail,
            }]
        },
        {
            path: '/roleList',
            component: Role
        }
    ]
})

新建UserDetail:

<template>
    <font color="red">用户id:{{this.$route.params.id}}</font>
</template>

UserDetail是属于UserList子页面属于它的一部分 说以需要在UserList加上路由标签

<template>
    <div>
        <table>
            <tr><td>用户id</td><td>用户姓名</td></tr>
            <tr v-for="u in userList"><td>{{u.id}}</td><td>{{u.name}}</td></tr>
        </table>
        <router-view></router-view>
    </div>

</template>
<script>
  export default {
        data:function () {
            return {
                userList:[
                    {id:1,name:"张三"},
                    {id:2,name:"李四"}
                ]
            }
        }
  }
</script>
<style>

</style>

3.1.3 路由常用操作

  • router是VueRouter的一个对象,通过Vue.use(VueRouter)和VueRouter构造函数得到一个router的实例对象,
    这个对象中是一个全局的对象,他包含了所有的路由包含了许多关键的对象和属性。
  • route是一个跳转的路由对象,每一个路由都会有一个route对象,是一个局部的对象,可以获取对应的name,path,params,query等
    对应值就是当前路径对应的路由。

控件中获取当前路由对象

 当前路由路径:{{this.$route.path}}
 当前路由参数:{{this.$route.params.参数名称}}

跳转到指定路由

this.$router.push("/roleList")

其他路由操作参考

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值