一、 组件component
1. 什么是组件?
组件(Component)是 Vue.js 最强大的功能之一。组件可以扩展 HTML 元素,封装可重用的代码
组件是自定义元素(对象)
2. 定义组件的方式
方式1:先创建组件构造器,然后由组件构造器创建组件
方式2:直接创建组件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>定义组件的两种方式</title> <script src="js/vue.js"></script> </head> <body> <div id="itany"> <hello></hello> <my-world></my-world> </div> <script> /** * 方式1:先创建组件构造器,然后由组件构造器创建组件 */ //1.使用Vue.extend()创建一个组件构造器 var MyComponent=Vue.extend({ template:'<h3>Hello World</h3>' }); //2.使用Vue.component(标签名,组件构造器),根据组件构造器来创建组件 Vue.component('hello',MyComponent); /** * 方式2:直接创建组件(推荐) */ // Vue.component('world',{ Vue.component('my-world',{ template:'<h1>你好,世界</h1>' }); var vm=new Vue({ //这里的vm也是一个组件,称为根组件Root el:'#itany', data:{ msg:'heheda' } }); </script> </body> </html>
3. 组件的分类
分类:全局组件、局部组件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>组件的分类</title> <script src="js/vue.js"></script> </head> <body> <div id="itany"> <my-hello></my-hello> <my-world></my-world> </div> <script> /** * 全局组件,可以在所有vue实例中使用 */ Vue.component('my-hello',{ template:'<h3>{{name}}</h3>', data:function(){ //在组件中存储数据时,必须以函数形式,函数返回一个对象 return { name:'alice' } } }); /** * 局部组件,只能在当前vue实例中使用 */ var vm=new Vue({ el:'#itany', data:{ name:'tom' }, components:{ //局部组件 'my-world':{ template:'<h3>{{age}}</h3>', data(){ return { age:25 } } } } }); </script> </body> </html>
4. 引用模板
将组件内容放到模板<template>中并引用
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>引用模板</title> <script src="js/vue.js"></script> </head> <body> <div id="itany"> <my-hello></my-hello> <my-hello></my-hello> </div> <template id="wbs"> <!-- <template>必须有且只有一个根元素 --> <div> <h3>{{msg}}</h3> <ul> <li v-for="value in arr">{{value}}</li> </ul> </div> </template> <script> var vm=new Vue({ el:'#itany', components:{ 'my-hello':{ name:'wbs17022', //指定组件的名称,默认为标签名,可以不设置 template:'#wbs', data(){ return { msg:'欢迎来到南京网博', arr:['tom','jack','mike'] } } } } }); </script> </body> </html>
5. 动态组件
<!-- 动态组件由 vm 实例的属性值 `componentId` 控制 -->
<component :is="componentId"></component>
<!-- 也能够渲染注册过的组件或 prop 传入的组件 -->
<component :is="$options.components.child"></component>
<keep-alive>组件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>动态组件</title> <script src="js/vue.js"></script> </head> <body> <div id="itany"> <button @click="flag='my-hello'">显示hello组件</button> <button @click="flag='my-world'">显示world组件</button> <div> <!-- 使用keep-alive组件缓存非活动组件,可以保留状态,避免重新渲染,默认每次都会销毁非活动组件并重新创建 --> <keep-alive> <component :is="flag"></component> </keep-alive> </div> </div> <script> var vm=new Vue({ el:'#itany', data:{ flag:'my-hello' }, components:{ 'my-hello':{ template:'<h3>我是hello组件:{{x}}</h3>', data(){ return { x:Math.random() } } }, 'my-world':{ template:'<h3>我是world组件:{{y}}</h3>', data(){ return { y:Math.random() } } } } }); </script> </body> </html>
二、 组件间数据传递
1. 父子组件
在一个组件内部定义另一个组件,称为父子组件
子组件只能在父组件内部使用
默认情况下,子组件无法访问父组件中的数据,每个组件实例的作用域是独立的
2. 组件间数据传递 (通信)
2.1 子组件访问父组件的数据
a)在调用子组件时,绑定想要获取的父组件中的数据
b)在子组件内部,使用props选项声明获取的数据,即接收来自父组件的数据
总结:父组件通过props向下传递数据给子组件
注:组件中的数据共有三种形式:data、props、computed
2.2 父组件访问子组件的数据
a)在子组件中使用vm.$emit(事件名,数据)触发一个自定义事件,事件名自定义
b)父组件在使用子组件的地方监听子组件触发的事件,并在父组件中定义方法,用来获取数据
总结:子组件通过events给父组件发送消息,实际上就是子组件把自己的数据发送到父组件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>父子组件及组件间数据传递</title> <script src="js/vue.js"></script> </head> <body> <div id="itany"> <my-hello></my-hello> </div> <template id="hello"> <div> <h3>我是hello父组件</h3> <h3>访问自己的数据:{{msg}},{{name}},{{age}},{{user.username}}</h3> <h3>访问子组件的数据:{{sex}},{{height}}</h3> <hr> <my-world :message="msg" :name="name" :age="age" @e-world="getData"></my-world> </div> </template> <template id="world"> <div> <h4>我是world子组件</h4> <h4>访问父组件中的数据:{{message}},{{name}},{{age}},{{user.username}}</h4> <h4>访问自己的数据:{{sex}},{{height}}</h4> <button @click="send">将子组件的数据向上传递给父组件</button> </div> </template> <script> var vm=new Vue({ //根组件 el:'#itany', components:{ 'my-hello':{ //父组件 methods:{ getData(sex,height){ this.sex=sex; this.height=height; } }, data(){ return { msg:'网博', name:'tom', age:23, user:{id:9527,username:'唐伯虎'}, sex:'', height:'' } }, template:'#hello', components:{ 'my-world':{ //子组件 data(){ return { sex:'male', height:180.5 } }, template:'#world', // props:['message','name','age','user'] //简单的字符串数组 props:{ //也可以是对象,允许配置高级设置,如类型判断、数据校验、设置默认值 message:String, name:{ type:String, required:true }, age:{ type:Number, default:18, validator:function(value){ return value>=0; } }, user:{ type:Object, default:function(){ //对象或数组的默认值必须使用函数的形式来返回 return {id:3306,username:'秋香'}; } } }, methods:{ send(){ // console.log(this); //此处的this表示当前子组件实例 this.$emit('e-world',this.sex,this.height); //使用$emit()触发一个事件,发送数据 } } } } } } }); </script> </body> </html>
3. 单向数据流
props是单向绑定的,当父组件的属性变化时,将传导给子组件,但是不会反过来
而且不允许子组件直接修改父组件中的数据,报错
解决方式:
方式1:如果子组件想把它作为局部数据来使用,可以将数据存入另一个变量中再操作,不影响父组件中的数据
方式2:如果子组件想修改数据并且同步更新到父组件,两个方法:
a.使用.sync(1.0版本中支持,2.0版本中不支持,2.3版本又开始支持)
需要显式地触发一个更新事件
b.可以将父组件中的数据包装成对象,然后在子组件中修改对象的属性(因为对象是引用类型,指向同一个内存空间),推荐
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>单向数据流</title> <script src="js/vue.js"></script> </head> <body> <div id="itany"> <h2>父组件:{{name}}</h2> <input type="text" v-model="name"> <h2>父组件:{{user.age}}</h2> <hr> <my-hello :name.sync="name" :user="user"></my-hello> </div> <template id="hello"> <div> <h3>子组件:{{name}}</h3> <h3>子组件:{{user.age}}</h3> <button @click="change">修改数据</button> </div> </template> <script> var vm=new Vue({ //父组件 el:'#itany', data:{ name:'tom', user:{ name:'zhangsan', age:24 } }, components:{ 'my-hello':{ //子组件 template:'#hello', props:['name','user'], data(){ return { username:this.name //方式1:将数据存入另一个变量中再操作 } }, methods:{ change(){ // this.username='alice'; // this.name='alice'; // this.$emit('update:name','alice'); //方式2:a.使用.sync,需要显式地触发一个更新事件 this.user.age=18; } } } } }); </script> </body> </html>
4. 非父子组件间的通信
非父子组件间的通信,可以通过一个空的Vue实例作为中央事件总线(事件中心),用它来触发事件和监听事件
var Event=new Vue();
Event.$emit(事件名,数据);
Event.$on(事件名,data => {});
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>非父子组件间的通信</title> <script src="js/vue.js"></script> </head> <body> <div id="itany"> <my-a></my-a> <my-b></my-b> <my-c></my-c> </div> <template id="a"> <div> <h3>A组件:{{name}}</h3> <button @click="send">将数据发送给C组件</button> </div> </template> <template id="b"> <div> <h3>B组件:{{age}}</h3> <button @click="send">将数组发送给C组件</button> </div> </template> <template id="c"> <div> <h3>C组件:{{name}},{{age}}</h3> </div> </template> <script> //定义一个空的Vue实例 var Event=new Vue(); var A={ template:'#a', data(){ return { name:'tom' } }, methods:{ send(){ Event.$emit('data-a',this.name); } } } var B={ template:'#b', data(){ return { age:20 } }, methods:{ send(){ Event.$emit('data-b',this.age); } } } var C={ template:'#c', data(){ return { name:'', age:'' } }, mounted(){ //在模板编译完成后执行 Event.$on('data-a',name => { this.name=name; // console.log(this); }); Event.$on('data-b',age => { this.age=age; }); } } var vm=new Vue({ el:'#itany', components:{ 'my-a':A, 'my-b':B, 'my-c':C } }); </script> </body> </html>
三、 slot内容分发
本意:位置、槽
作用:用来获取组件中的原内容,类似angular中的transclude指令
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>slot内容分发</title> <script src="js/vue.js"></script> </head> <body> <div id="itany"> <!-- <my-hello>wbs17022</my-hello> --> <my-hello> <ul slot="s1"> <li>aaa</li> <li>bbb</li> <li>ccc</li> </ul> <ol slot="s2"> <li>111</li> <li>222</li> <li>333</li> </ol> </my-hello> </div> <template id="hello"> <div> <slot name="s2"></slot> <h3>welcome to itany</h3> <!-- <slot>如果没有原内容,则显示该内容</slot> --> <slot name="s1"></slot> </div> </template> <script> var vm=new Vue({ el:'#itany', components:{ 'my-hello':{ template:'#hello' } } }); </script> </body> </html>
四、 vue-router路由
1. 简介
使用Vue.js开发SPA(Single Page Application)单页面应用
根据不同url地址,显示不同的内容,但显示在同一个页面中,称为单页面应用
[参考](https://router.vuejs.org/zh-cn)
bower info vue-router
cnpm install vue-router -S
2. 基本用法
a.布局
b.配置路由
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>路由基本用法</title> <style> /* .router-link-active{ font-size:20px; color:#ff7300; text-decoration:none; } */ .active{ font-size:20px; color:#ff7300; text-decoration:none; } </style> <script src="js/vue.js"></script> <script src="js/vue-router.js"></script> </head> <body> <div id="itany"> <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:'/home'} //重定向 ] //3.创建路由实例 const router=new VueRouter({ routes, //简写,相当于routes:routes // mode:'history', //更改模式 linkActiveClass:'active' //更新活动链接的class类名 }); //4.创建根实例并将路由挂载到Vue实例上 new Vue({ el:'#itany', router //注入路由 }); </script> </body> </html>
3. 路由嵌套和参数传递
传参的两种形式:
a.查询字符串:login?name=tom&pwd=123
{{$route.query}}
b.rest风格url:regist/alice/456
{{$route.params}}
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>路由嵌套和参数传递</title> <link rel="stylesheet" href="css/animate.css"> <style> .active{ font-size:20px; color:#ff7300; text-decoration:none; } </style> <script src="js/vue.js"></script> <script src="js/vue-router.js"></script> </head> <body> <div id="itany"> <div> <router-link to="/home">主页</router-link> <router-link to="/user">用户</router-link> </div> <div> <transition enter-active-class="animated bounceInLeft" leave-active-class="animated bounceOutRight"> <router-view></router-view> </transition> </div> <hr> <button @click="push">添加路由</button> <button @click="replace">替换路由</button> </div> <template id="user"> <div> <h3>用户信息</h3> <ul> <router-link to="/user/login?name=tom&pwd=123" tag="li">用户登陆</router-link> <router-link to="/user/regist/alice/456" tag="li">用户注册</router-link> </ul> <router-view></router-view> </div> </template> <script> var Home={ template:'<h3>我是主页</h3>' } var User={ template:'#user' } var Login={ template:'<h4>用户登陆。。。获取参数:{{$route.query}},{{$route.path}}</h4>' } var Regist={ template:'<h4>用户注册。。。获取参数:{{$route.params}},{{$route.path}}</h4>' } const routes=[ { path:'/home', component:Home }, { path:'/user', component:User, children:[ { path:'login', component:Login }, { path:'regist/:username/:password', component:Regist } ] }, { path:'*', redirect:'/home' } ] const router=new VueRouter({ routes, //简写,相当于routes:routes linkActiveClass:'active' //更新活动链接的class类名 }); new Vue({ el:'#itany', router, //注入路由 methods:{ push(){ router.push({path:'home'}); //添加路由,切换路由 }, replace(){ router.replace({path:'user'}); //替换路由,没有历史记录 } } }); </script> </body> </html>
4. 路由实例的方法
router.push() 添加路由,功能上与<route-link>相同
router.replace() 替换路由,不产生历史记录
5. 路由结合动画
五、 单文件组件
1. .vue文件
.vue文件,称为单文件组件,是Vue.js自定义的一种文件格式,一个.vue文件就是一个单独的组件,在文件内封装了组件相关的代码:html、css、js
.vue文件由三部分组成:<template>、<style>、<script>
<template>
html
</template>
<style>
css
</style>
<script>
js
</script>
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就是一个模块加载器,所有资源都可以作为模块来加载,最后打包输出
[官网](http://webpack.github.io/)
webpack版本:v1.x v2.x
webpack有一个核心配置文件:webpack.config.js,必须放在项目根目录下
4. 示例,步骤:
4.1 创建项目,目录结构 如下:
webpack-demo
|-index.html
|-main.js 入口文件
|-App.vue vue文件
|-package.json 工程文件
|-webpack.config.js webpack配置文件
|-.babelrc Babel配置文件
4.2 编写App.vue
<template> <div id="app"> <h1>{{msg}}</h1> </div> </template> <script> export default { name: 'app', data () { return { msg: 'Welcome to itany' } } } </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; } h1, h2 { font-weight: normal; } ul { list-style-type: none; padding: 0; } li { display: inline-block; margin: 0 10px; } a { color: #42b983; } </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 -D 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
4.4 编写main.js
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', template: '<App/>', components: { App } })
4.5 编写webpack.config.js
var path = require('path') var webpack = require('webpack') module.exports = { entry: './src/main.js', output: { path: path.resolve(__dirname, './dist'), publicPath: '/dist/', filename: 'build.js' }, module: { rules: [ { test: /\.vue$/, loader: 'vue-loader', options: { loaders: { } // other vue-loader options go here } }, { test: /\.js$/, loader: 'babel-loader', exclude: /node_modules/ }, { test: /\.(png|jpg|gif|svg)$/, loader: 'file-loader', options: { name: '[name].[ext]?[hash]' } } ] }, resolve: { alias: { 'vue$': 'vue/dist/vue.esm.js' } }, devServer: { historyApiFallback: true, noInfo: true }, performance: { hints: false }, devtool: '#eval-source-map' } if (process.env.NODE_ENV === 'production') { module.exports.devtool = '#source-map' // http://vue-loader.vuejs.org/en/workflow/production.html module.exports.plugins = (module.exports.plugins || []).concat([ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: '"production"' } }), new webpack.optimize.UglifyJsPlugin({ sourceMap: true, compress: { warnings: false } }), new webpack.LoaderOptionsPlugin({ minimize: true }) ]) }
4.6 编写.babelrc
{ "presets": [ ["env", { "modules": false }] ] }
4.7 编写package.json
{ "name": "itan", "description": "A Vue.js project", "version": "1.0.0", "author": "itany <[email protected]>", "private": true, "scripts": { "dev": "cross-env NODE_ENV=development webpack-dev-server --open --hot", "build": "cross-env NODE_ENV=production webpack --progress --hide-modules" }, "dependencies": { "vue": "^2.3.3" }, "devDependencies": { "babel-core": "^6.0.0", "babel-loader": "^6.0.0", "babel-preset-env": "^1.5.1", "cross-env": "^3.0.0", "css-loader": "^0.25.0", "file-loader": "^0.9.0", "vue-loader": "^12.1.0", "vue-template-compiler": "^2.3.3", "webpack": "^2.6.1", "webpack-dev-server": "^2.4.5" } }
4.8 运行测试
npm run dev
六、 vue-cli脚手架
1. 简介
vue-cli是一个vue脚手架,可以快速构造项目结构
vue-cli本身集成了多种项目模板:
simple 很少简单
webpack 包含ESLint代码规范检查和unit单元测试等
webpack-simple 没有代码规范检查和单元测试
browserify 使用的也比较多
browserify-simple
2. 示例,步骤:
2.1 安装vue-cli,配置vue命令环境
cnpm install vue-cli -g
vue --version
vue list
2.2 初始化项目,生成项目模板
语法:vue init 模板名 项目名
2.3 进入生成的项目目录,安装模块包
cd vue-cli-demo
cnpm install
2.4 运行
npm run dev //启动测试服务
npm run build //将项目打包输出dist目录,项目上线的话要将dist目录拷贝到服务器上
3. 使用webpack模板
vue init webpack vue-cli-demo2
ESLint是用来统一代码规范和风格的工具,如缩进、空格、符号等,要求比较严格
[官网](http://eslint.org)
问题Bug:如果版本升级到node 8.0 和 npm 5.0,控制台会报错:
GET http://localhost:8080/__webpack_hmr net::ERR_INCOMPLETE_CHUNKED_ENCODING
解决方法:
a)降低Node版本到7.9或以下
b)修改build/dev-server.js文件,如下:
var hotMiddleware = require('webpack-hot-middleware')(compiler, {
log: () => {},
heartbeat:2000 //添加此行
})
参考:https://github.com/vuejs-templates/webpack/issues/731