## 一、 組件component
### 1. 什麼是組件?
組件(Component)是 Vue.js 最強大的功能之一。組件可以擴展 HTML 元素,封裝可重用的代碼
組件是自定義元素(對象)
### 2. 定義組件的方式
方式1:先創建組件構造器,然後由組件構造器創建組件
方式2:直接創建組件
### 3. 組件的分類
分類:全局組件、局部組件
### 4. 引用模板
將組件內容放到模板<template>中並引用
### 5. 動態組件
<component :is="">組件
多個組件使用同一個掛載點,然後動態的在它們之間切換
<keep-alive>組件
## 二、 組件間數據傳遞
### 1. 父子組件
在一個組件內部定義另一個組件,稱爲父子組件
子組件只能在父組件內部使用
默認情況下,子組件無法訪問父組件中的數據,每個組件實例的作用域是獨立的
### 2. 組件間數據傳遞 (通信)
#### 2.1 子組件訪問父組件的數據
a)在調用子組件時,綁定想要獲取的父組件中的數據
b)在子組件內部,使用props選項聲明獲取的數據,即接收來自父組件的數據
總結:父組件通過props向下傳遞數據給子組件
注:組件中的數據共有三種形式:data、props、computed
#### 2.2 父組件訪問子組件的數據
a)在子組件中使用vm.$emit(事件名,數據)觸發一個自定義事件,事件名自定義
b)父組件在使用子組件的地方監聽子組件觸發的事件,並在父組件中定義方法,用來獲取數據
總結:子組件通過events給父組件發送消息,實際上就是子組件把自己的數據發送到父組件
### 3. 單向數據流
props是單向綁定的,當父組件的屬性變化時,將傳導給子組件,但是不會反過來
而且不允許子組件直接修改父組件中的數據,報錯
解決方式:
方式1:如果子組件想把它作爲局部數據來使用,可以將數據存入另一個變量中再操作,不影響父組件中的數據
方式2:如果子組件想修改數據並且同步更新到父組件,兩個方法:
a.使用.sync(1.0版本中支持,2.0版本中不支持,2.3版本又開始支持)
需要顯式地觸發一個更新事件
b.可以將父組件中的數據包裝成對象,然後在子組件中修改對象的屬性(因爲對象是引用類型,指向同一個內存空間),推薦
### 4. 非父子組件間的通信
非父子組件間的通信,可以通過一個空的Vue實例作爲中央事件總線(事件中心),用它來觸發事件和監聽事件
var Event=new Vue();
Event.$emit(事件名,數據);
Event.$on(事件名,data => {});
## 三、 slot內容分發
本意:位置、槽
作用:用來獲取組件中的原內容,類似angular中的transclude指令
## 四、 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.配置路由
### 3. 路由嵌套和參數傳遞
傳參的兩種形式:
a.查詢字符串:login?name=tom&pwd=123
{{$route.query}}
b.rest風格url:regist/alice/456
{{$route.params}}
### 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
### 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
### 4.5 編寫webpack.config.js
### 4.6 編寫.babelrc
### 4.7 編寫package.json
### 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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>自定義組件的2中方式</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 MyComponnet = Vue.extend({
template:'<h3>Hello World</h3>'
});
//2.使用Vue.component(標籤名,組件構造器),根據組件構造器來創建組件
Vue.component('hello',MyComponnet);
/**
* 方式2 :直接創建組件(推薦)
*/
//Vue.component('world',{})
Vue.component('my-world',{
template:'<h1>你好,世界</h1>'
});
var vm = new Vue({ //這裏的vm 也是一個組件,稱爲根組件Root
el:'#itany',
data:{
msg:'馬納山'
}
})
</script>
</body>
</html>
<!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>
<!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>
<!DOCTYPE html>
<html>
<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>
<!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>
<!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>
<!DOCTYPE html>
<html>
<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>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>slot內容分發</title>
<script src="js/vue.js"></script>
</head>
<body>
//分發div 中的內容
<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>
<!DOCTYPE html>
<html>
<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>
<!DOCTYPE html>
<html>
<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>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>購物車</title>
<link rel="stylesheet" href="bootstrap/bootstrap.min.css">
</head>
<body>
<div id="app" class="container">
<h2 class="text-center">購物車</h2>
<table class="table table-bordered table-hover table-condensed">
<thead>
<tr>
<th class="text-center">商品編號</th>
<th class="text-center">商品名稱</th>
<th class="text-center">購買數量</th>
<th class="text-center">商品單價</th>
<th class="text-center">商品總價</th>
<th class="text-center">操作</th>
</tr>
</thead>
<tbody>
<tr v-for="(item,index) in commodities" class="text-center">
<td>{{item.id}}</td>
<td>{{item.name}}</td>
<td>
<button class="btn btn-primary" @click="subtract(index)">-</button>
<input type="text" v-model="item.quantity">
<button class="btn btn-primary" @click="add(index)">+</button>
</td>
<td>{{item.price | filterMoney}}</td>
<td>{{item.price*item.quantity | filterMoney}}</td>
<td>
<button class="btn btn-danger" @click="remove(index)">移除</button>
</td>
</tr>
<tr>
<td colspan="2">總數量:{{totalNum}}</td>
<td colspan="2">總金額:{{totalMoney | filterMoney}}</td>
<td colspan="2">
<button class="btn btn-danger" @click="empty()">清空購物車</button>
</td>
</tr>
<tr v-show="commodities.length===0">
<td colspan="6" class="text-center text-muted">
<p>您的購物車空空如也....</p>
</td>
</tr>
</tbody>
</table>
</div>
<script src="https://unpkg.com/[email protected]"></script>
<script src="js/vue.js"></script>
<script>
var vm = new Vue({
el: "#app",
data: {
commodities: [
{id: 1001,name: 'iphone5s',quantity: 3,price: 4000},
{id: 1005,name: 'iphone6',quantity: 9,price: 5000},
{id: 2001,name: 'imac',quantity: 4,price: 7000},
{id: 2004,name: 'ipad',quantity: 5,price: 2000}
]
},
computed: {
totalNum:function(){
var sum=0;
this.commodities.forEach(function(item){ //ES5新增方法forEach()
sum+=item.quantity;
});
return sum;
},
totalMoney: function() {
/* var sum=0;
this.commodities.forEach(function(item){ //ES5新增方法forEach()
sum+=item.price*item.quantity;
});
return sum;*/
return this.commodities.reduce(function(prev,cur,index,array) { //ES5新增方法reduce()
return prev+cur.price*cur.quantity;
},0);
}
},
filters: {
filterMoney: function(value) {
return '¥' + value;
}
},
methods: {
add: function(index) {
this.commodities[index].quantity++;
},
subtract: function(index) {
var item=this.commodities[index];
if (item.quantity == 1) {
if (confirm(`確定要刪除商品:${item.name} 嗎?`)) {
this.commodities.splice(index, 1);
}
return;
}
item.quantity--;
},
remove: function(index) {
if (confirm(`確定要刪除商品:${this.commodities[index].name} 嗎?`)) {
this.commodities.splice(index, 1)
}
},
empty: function() {
// this.commodities.splice(0, this.commodities.length);
this.commodities=[];
}
}
});
</script>
</body>
</html>