vue2.0入门教程

Vue是渐进式——易用、灵活、高效,没有太多限制的JavaScript框架

两种使用方式

1.引入cdn
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
2.命令行工具搭建脚手架
el属性:element需要获取的元素,一定是html中的根容器元素
data属性:用于数据的存储,本质是对象,key和value自定义

初始vue双花括号中的内容放入了一个虚拟dom通过它插入dom中
在Vue中可以直接拿到属性在方法中使用
Index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue.js</title>
    <link rel="stylesheet" href="style.css">
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body>
    <!-- vue-app是根容器 -->
    <div id="vue-app">
        <h1>{{ greet('night') }}</h1>
        <p>Name: {{ name }}</p>
        <p>Job: {{ job }}</p>
    </div>
    <script src="app.js"></script>
</body>
</html>

app.js

//实例化vue对象
new Vue({
    el:"#vue-app",
    data:{
        name:"米斯特",
        job:"web开发"
    },
    methods:{

        greet: function(time){
            return 'Good '+ time +" " +this.name + "!";
        }
    }
});

/*
*el:element 需要获取的元素,一定是html中的根容器元素
*data:用于数据的存储
*methods:用于存储各种方法
*/

属性绑定

  • v-bind绑定值
  • v-html绑定标签
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue.js</title>
    <link rel="stylesheet" href="style.css">
    <script src="https://cdn.jsdelivr.net/npm/vue"></script>
</head>
<body>
    <!-- vue-app是根容器 -->
    <div id="vue-app">
        <h1>{{ greet('night') }}</h1>
        <p>Name: {{ name }}</p>
        <p>Job: {{ job }}</p>
        <a v-bind:href="website">web开发</a>
        <input type="text" v-bind:value="job">
        <p v-html="websiteTag"></p>
    </div>
    <script src="app.js"></script>
</body>
</html>
//实例化vue对象
new Vue({
    el:"#vue-app",
    data:{
        name:"米斯特",
        job:"web开发",
        website:"http://www.thenewstep.com",
        websiteTag:"<a href='http:www.thenewstep.com'>Thenewstep</a>"
    },
    methods:{
        greet: function(time){
            return 'Good '+ time +" " +this.name + "!";
        }
    }
});

/*
*el:element 需要获取的元素,一定是html中的根容器元素
*data:用于数据的存储
*methods:用于存储各种方法
*data-binding:给属性绑定对应的值
*/

事件

  • v-on:click点击事件
  • v-on:dblclick双击事件
  • v-on:mousemove鼠标事件
    使用“@”代替”v-on:”
    Index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue.js</title>
    <link rel="stylesheet" href="style.css">
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
    <div id="vue-app">
        <h1> Events </h1>
        <button @click="add(1)">涨一岁</button>
        <button v-on:click="subtract(1)">减一岁</button>
        <button @dblclick="add(10)">涨十岁</button>
        <button v-on:dblclick="subtract(10)">减十岁</button>
        <p>My age is {{age}}</p>

        <div id="canvas" v-on:mousemove="updateXY">
            {{x}},{{y}}
        </div>
    </div>

    <script src="app.js"></script>
</body>
</html>

app.js

//实例化vue对象
new Vue({
    el:"#vue-app",
    data:{
        age:30,
        x:0,
        y:0
    },
    methods:{
        add :function(inc){
            this.age += inc;
        },
        subtract :function(dec){
            this.age -= dec;
        },
        updateXY:function(event){
            //console.log(event);
            this.x = event.offsetX;
            this.y = event.offsetY;
        }
    }
});

style.css

#canvas{
    width: 600px;
    padding: 200px 20px;
    text-align: center;
    border: 1px solid #333;
}
});

事件修饰符once:prev:stop

  • once只有一次被触发
  • prev不做跳转
  • stop时间停止器
    index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue.js</title>
    <link rel="stylesheet" href="style.css">
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
    <div id="vue-app">
        <h1> Events </h1>
        <button @click.once="add(1)">涨一岁</button>
        <button v-on:click="subtract(1)">减一岁</button>
        <button @dblclick="add(10)">涨十岁</button>
        <button v-on:dblclick="subtract(10)">减十岁</button>
        <p>My age is {{age}}</p>

        <div id="canvas" v-on:mousemove="updateXY">
            {{x}} , {{y}} - 
            <span v-on:mousemove.stop=""> Stop Moving
            </span>
        </div>
        <a v-on:click.prevent="alert()" href="http://www.thenewstep.com">The new step</a>
    </div>

    <script src="app.js"></script>
</body>
</html>

app.js

new Vue({
    el:"#vue-app",
    data:{
        age:30,
        x:0,
        y:0
    },
    methods:{
        add :function(inc){
            this.age += inc;
        },
        subtract :function(dec){
            this.age -= dec;
        },
        updateXY:function(event){
            //console.log(event);
            this.x = event.offsetX;
            this.y = event.offsetY;
        },
        StopMoving:function(event){
            event.stopPropagation();
        },
        alert:function(){
            alert("Hello World");
        }
    }
});

键盘事件和键值修饰符

v-on:keyup
Index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue.js</title>
    <link rel="stylesheet" href="style.css">
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
    <div id="vue-app">
        <h1> 键盘 Events </h1>
        <label>姓名:</label>
        <input type="text" v-on:keyup.enter="logName">
        <label>年龄</label>
        <input type="text" v-on:keyup.alt.enter="logAge">   
    </div>

    <script src="app.js"></script>
</body>
</html>

app.js

//实例化vue对象
new Vue({
    el:"#vue-app",
    data:{

    },
    methods:{
        logName:function(){
            console.log("你正在输入名字!");
        },
        logAge:function(){
            console.log("你正在输入年龄!");
        },
    }
});

双向数据绑定

  • 把属性绑定到元素,输出也决定标签的值
  • Input、select、textarea这三个标签选择输入
  • ref进行标记,可以再refs调用标记好的属性

    Index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue.js</title>
    <link rel="stylesheet" href="style.css">
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
    <div id="vue-app">
        <h1> 双向数据绑定 / input  / select / textarea </h1>
        <label>姓名:</label>
        <input ref="name" type="text">
        <span>{{name}}</span>
        <label>年龄:</label>
        <input ref="age" type="text">   
        <span>{{age}}</span> 
    </div>

    <script src="app.js"></script>
</body>
</html>

app.js

//实例化vue对象
new Vue({
    el:"#vue-app",
    data:{
        name:"",
        age:""
    },
    methods:{
        logName:function(){
            //console.log("你正在输入名字!");
            this.name = this.$refs.name.value;
            //console.log(this.$refs.name.value);
        }, 
        logAge:function(){
            //console.log("你正在输入年龄!");
            this.age = this.$refs.age.value; 
        },
    }
});

v-model帮助实现事件双向绑定
Index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue.js</title>
    <link rel="stylesheet" href="style.css">
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
    <div id="vue-app">
        <h1> 双向数据绑定 / input  / select / textarea </h1>
        <label>姓名:</label>
        <input ref="name" type="text" v-model="name">
        <span>{{name}}</span>
        <label>年龄:</label>
        <input ref="age" type="text" v-model="age"> 
        <span>{{age}}</span> 
    </div>

    <script src="app.js"></script>
</body>
</html>

app.js

//实例化vue对象
new Vue({
    el:"#vue-app",
    data:{
        name:"",
        age:""
    },
    methods:{
        logName:function(){
            //console.log("你正在输入名字!");
            //this.name = this.$refs.name.value;
            //console.log(this.$refs.name.value);
        }, 
        logAge:function(){
            //console.log("你正在输入年龄!");
            //this.age = this.$refs.age.value; 
        },
    }
});

计算属性Computed

当前dom变化幅度较大,如搜索时耗时,大量搜索,减少项目支出,优化项目,使用计算属性。
Index.html

 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Vue.js</title>
    <link rel="stylesheet" href="style.css">
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
    <div id="vue-app">
        <h1> Computed 计算属性 </h1>
        <button v-on:click="a++">Add to A</button>
        <button v-on:click="b++">Add to B</button>
        <p>A - {{a}}</p>
        <p>B - {{b}}</p>
        <p>Age + A ={{addToA}}</p>
        <p>Age + B ={{addToB}}</p>
    </div>

    <script src="app.js"></script>
</body>
</html>

app.js

new Vue({
    el:"#vue-app",
    data:{
        a:0,
        b:0,
        age:20
    },
    methods:{
        /*
        addToA:function(){
            console.log("Add to A");
            return this.a + this.age;
        },
        addToB:function(){
            console.log("Add to B");
            return this.b + this.age;   
        }
        */
    },
    computed:{
        addToA:function(){
            console.log("Add to A");
            return this.a + this.age;
        },
        addToB:function(){
            console.log("Add to B");
            return this.b + this.age;   
        } 
    }
});

当虚拟dom和真实dom不同时才触发计算属性方法。虚拟dom和真实dom相同,则不会触发计算属性的方法,而methods方法中内容不管如何都会触发全都。

Vue动态绑定CSS样式

Index.html

<!DOCTYPE html>
<html lang="en">
<head>  
    <meta charset="UTF-8">
    <title>Vue.js</title>
    <link rel="stylesheet" href="style.css">
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
    <div id="vue-app">
        <h1> 动态 CSS Class </h1>

        <h2>示例 1</h2>
        <!-- <div v-on:click="changeColor = !changeColor" v-bind:class="{changeColor}">
            <span>Henry</span>
        </div> -->

        <h2>示例 2</h2>
        <button v-on:click="changeColor = !changeColor">changeColor</button>
        <button v-on:click="changeLength = !changeLength">changeLength</button>
        <div v-bind:class="compClasses">
            <span>Henry </span>
        </div>
    </div>

    <script src="app.js"></script>
</body>
</html>

style.css

span{
    background:red;
    display: inline-block;
    padding: 10px;
    color: #fff;
    margin: 10px 0;
}

.changeColor span{
    background: green;
}

.changeLength span:after{
    content: "length";
    margin-left: 10px;
}

app.js

new Vue({
    el:"#vue-app",
    data:{
        changeColor:false,
        changeLength:false
    },
    methods:{

    },
    computed:{
        compClasses:function(){
            return {
                changeColor:this.changeColor,
                changeLength:this.changeLength
            }
        }
    }
});

使用v-bind动态绑定属性,方法中是对象。

在示例1中,动态绑定的class属性,在style.css中的属性是把背景颜色的样式改为绿,点击事件是把changeColor属性取反。渲染前changeColor属性为false不显示,点击之后,class属性改变。

在示例2中,两个按钮用来更改颜色和样式,点击事件是把changeColor/changeLength属性取反。Div绑定属性使用的计算属性,传递的是一个compClasses对象。compClasses对象传递changeColor或者changeLength属性

指令v-if

  • 并不占位或者消失,逻辑if-else-if控制选择
  • v-show占位的,标签的display属性控制
    Index.html
<!DOCTYPE html>
<html lang="en">
<head>  
    <meta charset="UTF-8">
    <title>Vue.js</title>
    <link rel="stylesheet" href="style.css">
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
    <div id="vue-app">
        <h1> v- if 条件 </h1>

        <button v-on:click="error = !error">Toggle Error</button>
        <button v-on:click="success = !success">Toggle Success</button>

        <!-- <p v-if="error">网络连接错误:404</p>
        <p v-else-if="success">网络连接成功:200</p> -->
        <p v-show="error">网络连接错误:404</p>
        <p v-show="success">网络连接成功:200</p>

    </div>

    <script src="app.js"></script>
</body>
</html>

app.js

new Vue({
    el:"#vue-app",
    data:{
        error:false,
        success:false
    },
    methods:{

    },
    computed:{

    }
});

指令v-for

不仅可以遍历数组,同样适用于对象,使用数组遍历出来的每个元素成为对象,类似于 v-if,可以利用带有 v-for 的 渲染多个元素
Index.html

<!DOCTYPE html>
<html lang="en">
<head>  
    <meta charset="UTF-8">
    <title>Vue.js</title>
    <link rel="stylesheet" href="style.css">
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
    <div id="vue-app">
        <h1> v-for 循环  </h1>
         <!-- 数组下标 -->
        <!-- {{characters[0]}}
        {{characters[1]}}
        {{characters[2]}}  -->

        <!-- 数组遍历 -->
        <ul>
            <li v-for="character in characters">
                {{character}}
            </li>
        </ul>

        <ul>
            <li v-for="(user,index) in users">
                 {{index+1}} .{{user.name}} - {{user.age}}
            </li>   
        </ul>

        <template v-for="(user,index) in users">
            <h3>{{index}} . {{user.name}}</h3>
            <p>Age - {{user.age}}</p>
        </template>

        <template v-for="(user,index) in users">
            <div v-for="(val,key) in user">
                <p>{{key}} - {{val}}</p>
            </div>
        </template> 
    </div>

    <script src="app.js"></script>
</body>
</html>

app.js

new Vue({
    el:"#vue-app",
    data:{
        characters:["Mario","Luffy","Yoshi"],
        users:[
            {name:"Henry",age:30},
            {name:"Bucky",age:25},
            {name:"Emily",age:18}
        ]
    },
    methods:{

    },
    computed:{

    }
});

实例化多个Vue对象

  通过类似定义变量的方式定义one、two两个vue对象,title显示标题的内容,在计算属性中,分别返回对应的greet方法。
  在two对象中,可以直接访问one的标题,使用方法去更改one对象的标题,在外部也可以访问到two的title,直接引用对象的标题更改。
index.html

<!DOCTYPE html>
<html lang="en">
<head>  
    <meta charset="UTF-8">
    <title>Vue.js</title>
    <link rel="stylesheet" href="style.css">
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
    <h1>初始化多个Vue实例对象</h1>
    <div id="vue-app-one">
        <h2>{{title}}</h2>
        <p>{{greet}}</p>
    </div>

    <div id="vue-app-two">
        <h2>{{title}}</h2>
        <p>{{greet}}</p>
        <button v-on:click="changeTitle">Change App One Title</button>
    </div>

    <script src="app.js"></script>
</body>
</html>

app.js

var one = new Vue({
    el:"#vue-app-one",
    data:{
        title:"app one的内容"
    },
    methods:{

    },
    computed:{
        greet:function(){
            return "Hello App One";
        }
    }
}); 

var two = new Vue({
    el:"#vue-app-two",
    data:{
        title:"app two的内容"
    },
    methods:{
        changeTitle:function(){
            one.title = "已经改名了!"
        }
    },
    computed:{
        greet:function(){
            return "Hello App Two";
        }
    }
}); 

two.title = "app two的title也发生变化了!";

初始组建的应用

组件的作用:整个组件大大优化代码,也可减少代码量。

1.使用Vue调用component方法,1名字,2传过去一个对象,包含data,method更多属性使用template模板展示html中,把comp当作标签使用,直接加DOM。

2.把应该展示在html中的name属性,直接在template模板中调用。很多公共的问题处理到组件,两个实例化对象都可以使用组件

3.模板里有且仅有一个根标签。

4.ES6语法换行用。在p标签中显示内容,在data属性中返回name值,在方法中使用changeName,来更改name的值。

5.如果不return对象,直接return 属性的话,那就是共享式,One和Two相同的属性都会更改。

index.html

<!DOCTYPE html>
<html lang="en">
<head>  
    <meta charset="UTF-8">
    <title>Vue.js</title>
    <link rel="stylesheet" href="style.css">
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
    <h1>初始Vue组件</h1>
    <div id="vue-app-one">
        <greeting></greeting>
    </div>

    <div id="vue-app-two">
        <greeting></greeting>
    </div>

    <script src="app.js"></script>
</body>
</html>

app.js

// var data = {
//  name:"小鹿哥"
// }

Vue.component("greeting",{
    template:`
    <p>
        {{name}}:大家好,给大家介绍一下我的女朋友@关晓彤
        <button v-on:click="changeName">改名</button>
    </p>
    `,
    data:function(){
        return{
                name:"鹿晗"
            }
        },
        methods:{
            changeName:function(){
                this.name = "M鹿M";
            }
        }
})


new Vue({
    el:"#vue-app-one",

}); 

new Vue({
    el:"#vue-app-two",

}); 

搭建脚手架CLI

脚手架是通过webpack搭建的开发环境
优势:

  • 使用ES6语法
  • 打包和压缩JS为一个文件
  • 项目文件在环境中编译,而不是浏览器
  • 实现页面的自动刷新
    要搭建脚手架,必须依赖的环境node.js

版本号要确定可以使用

  • node –v v6.9.x以上
  • npm –v v3.10.x以上

1.安装

npm install –global vue-cli
vue –version

2.vue cli已经装上,更改目录到项目根目录

vue init webpack my-project

3.花一点时间对项目模板下载
4.可以对项目起名,对项目进行描述;
vue-router目前用不到,不必安装,有需要自定义安装;
ESLint测试,模式变的严谨,不必要;
测试,不需要
这里写图片描述
5.在Vue-playlist目录下

目录作用
bulid构建客户端和服务端,可以改变端口号
config对应的一些配置
src做一些工作
staticstatic
.gitignore放置忽略的文件
index.html入口文件,对应的Vue插入到div容器中
package.json现在需要依赖的文件
REDADME.md对应的一些指令

6.npm run dev:开启一个8080端口,开展Vue项目

介绍SRC文件流程及根组件App

  • assets:放置图片
  • components:放置组件
  • App.vue:根组件

index.html入口文件,动态js插入到容器中,执行完index.html就会执行main.js中的内容,vue脚手架中从npm当中模块拿来使用
main.js

new Vue({
  el: '#app',//要获取的容器元素
  components: { App },//注册的组件名
  template: '<App/>'//模板,组件调用标签
})
// index.html -> main.js -> App.vue

App.vue

<!-- 1模板:html结构 -->
<template>
  <div id="app">
    <h1>{{title}}</h1>
  </div>
</template>

<!-- 2行为:处理逻辑 -->
<script>


export default {
  name: 'App',
  data(){
    return{
      title:"这是我的第一个VUe脚手架项目!"
    } 
  }
}
</script>

<!-- 3样式:解决样式 -->
<style>

</style>可以把组件理解为一个功能的页面

组件嵌套

新建一个Users.vue,搭建模板行为样式,在template中class名与组件名相同,与name名相同,使用v-for遍历users数组,设置一个全局变量回到App.vue添加,全局组件不安全,在App.vue中设置局部组件,展示App.Vue中的子组件,完成组件嵌套
Users.vue

<template>
  <div class="users">
    <ul>
      <li v-for="user in users">
          {{user}}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'users',
  data () {
    return {
      users:["Anne Hathaway","Kobe Bryant","Tom Cruise"]
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>

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'
//import Users from './component/Users'

Vue.config.productionTip = false

//全局注册组件
//Vue.component("users",Users);

/* eslint-disable no-new */
new Vue({
  el: '#app',
  components: { App },
  template: '<App/>'
})

// index.html -> main.js -> App.vue

App.vue

<!-- 1模板:html结构 -->
<template>
  <div id="app">
    <h1>{{title}}</h1>
    <users></users>
  </div>
</template>

<!-- 2行为:处理逻辑 -->
<script>

// 局部注册组件
import Users from './components/Users'

export default {
  name: 'App',
  data(){
    return{
      title:"这是我的第一个VUe脚手架项目!"
    } 
  },
  components:{
    Users
  }
}
</script>

<!-- 3样式:解决样式 -->
<style>

</style>

组件CSS作用域

样式直接在style中些css即可,使用scope属性让CSS在不同作用域工作。App.vue 中h1标签样式为紫色,Users.Vue中的h1标签样式为绿色
App.vue

<!-- 1模板:html结构 -->
<template>
  <div id="app">
    <h1>{{title}}</h1>
    <users></users>
  </div>
</template>

<!-- 2行为:处理逻辑 -->
<script>

// 局部注册组件
import Users from './components/Users'

export default {
  name: 'App',
  data(){
    return{
      title:"这是我的第一个VUe脚手架项目!"
    } 
  },
  components:{
    Users
  }
}
</script>

<!-- 3样式:解决样式 -->
<style scoped>
h1{
  color:purple;
}
</style>

Users.Vue

<template>
  <div class="users">
    <h1>Hello Users</h1>
    <ul>
      <li v-for="user in users">
          {{user}}
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'users',
  data () {
    return {
      users:["Anne Hathaway","Kobe Bryant","Tom Cruise"]
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1{
  color:green;
}
</style>

属性传值Props

Vue有两种传值方式:父组件给子组件传值/子组件给父组件传值。对App.vue来说,Users.vue,Header.vue,Footer.vue都是他的子组件,所以父组件App.vue给子组件Users.vue传users数组值,子组件使用props接收值。type属性表示传递类型,required:true是否规格,指定对象和制定属性,不建议直接使用数组的方式
App.vue

<template>
  <div id="app">
    <app-header></app-header>
    <app-users v-bind:users="users"></app-users>
    <app-footer></app-footer>
  </div>
</template>

<script>
import Header from './components/Header'
import Footer from './components/Footer'
import Users from './components/Users'
export default {
  name: 'app',
  components:{
    "app-header":Header,
    "app-footer":Footer,
    "app-users":Users
  },
  data(){
    return{
      // title:"这是我的第一个VUe脚手架项目!"
      users:[
      {name:"Lawson",position:"Web开发",show:false},
      {name:"Aalto",position:"Java开发",show:false},
      {name:"Pearl",position:"php开发",show:false},
      {name:"Mabel",position:"Python开发",show:false},
      {name:"Appleseed",position:"C++开发",show:false},
      {name:"Hadley",position:"Android开发",show:false},
      {name:"Nance",position:"Ios开发",show:false}
    ]
    }
  },
  methods:{

  }
}
</script>

<style scoped>

</style>

Users.Vue

<template>
  <div id="users">
    <ul>
        <li v-on:click="user.show = !user.show" 
            v-for="user in users">
            <h2>{{user.name}}</h2>
            <h3 v-show="user.show">
                {{user.position}}
            </h3>
        </li>
    </ul>
  </div>
</template>

<script>

export default {
  name: 'users',
  //props: ["users"],
  props:{
    users:{
    type:Array,
    required:true
    }
  },
  data(){
    return{

    }
  },
  methods:{

  }
}
</script>

<style scoped>
#users{
    width: 100%;
    max-width: 1200px;
    margin: 40px auto;
    padding: 0 20px;
    box-sizing: border-box;
}

ul{
    display: flex;
    flex-wrap: wrap;
    list-style-type: none;
    padding: 0;
}

li{
    flex-grow: 1;
    flex-basis: 300px;
    text-align: center;
    padding: 30px;
    border: 1px solid #222;
    margin: 10px;
}
</style>

传值和传引用

传值: string number boolean
引用:array object
类似于C语言传值和传址,传引用改变一个地方的数据所有和这个引用相关的数据都会发生变化,传值则不会更改
App.vue

<template>
  <div id="app">
    <app-header v-bind:title="title"></app-header>
    <app-users v-bind:users="users"></app-users>
    <app-users v-bind:users="users"></app-users>
    <app-footer v-bind:title="title"></app-footer>
  </div>
</template>

<script>
import Header from './components/Header'
import Footer from './components/Footer'
import Users from './components/Users'
export default {
  name: 'app',
  components:{
    "app-header":Header,
    "app-footer":Footer,
    "app-users":Users
  },
  data(){
    return{
      // title:"这是我的第一个VUe脚手架项目!"
      users:[
      {name:"Lawson",position:"Web开发",show:false},
      {name:"Aalto",position:"Java开发",show:false},
      {name:"Pearl",position:"php开发",show:false},
      {name:"Mabel",position:"Python开发",show:false},
      {name:"Appleseed",position:"C++开发",show:false},
      {name:"Hadley",position:"Android开发",show:false},
      {name:"Nance",position:"Ios开发",show:false}
    ],
    title:"传递的一个值(number string boolean)"
    }
  },
  methods:{

  }
}
</script>

<style scoped>

</style>

Header.vue

<template>
  <header v-on:click="changTitle">
    <h1>{{title1}}{{title}}</h1>
  </header>
</template>

<script>

export default {
  name:'app-header',
  props:{
    title:{
      type:String
    }
  },
  data(){
    return{
      title1:"Vue.js Demo"
    }
  },
  methods:{
    changTitle:function(){
      this.title = "changed";
    }
  }
}
</script>

<style scoped>
header{
    background: hotpink;
    padding: 10px;
}

h1{
    color: #eee;
    text-align: center;
}
</style>

Footer.vue

<template>
  <footer>
    <p>{{title1}}{{title}}</p>
  </footer>
</template>

<script>

export default {
  name:'app-footer',
  props:{
    title:{
      type:String
    }
  },
  data(){
    return{
      title1:"Copyright 2017 Vue.js"
    }
  },
  methods:{

  }
}
</script>

<style scoped>
footer{
    background: #eee;
    padding: 6px;
}

p{
    color: lightgreen;
    text-align: center;
}
</style>

事件传值(子to父)

子组件$emit传值,父组件$event接受子组件的值

实现方式:点击Header.vueheader标签来触发changeTitle方法,发现注册事件titleChanged,传递参数”子向父组件传值”,于是从App.vue父级中找到titleChanged事件,要执行updateTitle方法,在实现的地方updateTitle改变内容。改变内容后,在v-bindtitle就是刚刚传递的内容”子向父组件传值”,所以header和footer都会发生变化
Header.vue

<template>
  <header v-on:click="changTitle">
    <h1>{{title1}}{{title}}</h1>
  </header>
</template>

<script>

export default {
  name:'app-header',
  props:{
    title:{
      type:String
    }
  },
  data(){
    return{
      title1:"Vue.js Demo"
    }
  },
  methods:{
    changTitle:function(){
      //this.title = "changed";
      this.$emit("titleChanged","子向父组件传值");
    }
  }
}
</script>

<style scoped>
header{
    background: hotpink;
    padding: 10px;
}

h1{
    color: #eee;
    text-align: center;
}
</style>

App.vue

<template>
  <div id="app">
    <app-header v-on:titleChanged="updateTitle($event)" v-bind:title="title"></app-header>
    <app-users v-bind:users="users"></app-users>
    <app-users v-bind:users="users"></app-users>
    <app-footer v-bind:title="title"></app-footer>
  </div>
</template>

<script>
import Header from './components/Header'
import Footer from './components/Footer'
import Users from './components/Users'
export default {
  name: 'app',
  components:{
    "app-header":Header,
    "app-footer":Footer,
    "app-users":Users
  },
  data(){
    return{
      // title:"这是我的第一个VUe脚手架项目!"
      users:[
      {name:"Lawson",position:"Web开发",show:false},
      {name:"Aalto",position:"Java开发",show:false},
      {name:"Pearl",position:"php开发",show:false},
      {name:"Mabel",position:"Python开发",show:false},
      {name:"Appleseed",position:"C++开发",show:false},
      {name:"Hadley",position:"Android开发",show:false},
      {name:"Nance",position:"Ios开发",show:false}
    ],
    title:"传递的一个值(number string boolean)"
    }
  },
  methods:{
    updateTitle(title){
      this.title = title;
    }
  }
}
</script>

<style scoped>

</style>

生命周期(钩子函数)

从一个组件创建开始到结束的过程就是生命周期。生命周期可以用来
1.寻找错误
2.解决需求
  Mount即为挂载,执行beforeMount钩子函数在虚拟dom中执行,没有将真实内容渲染到页面上;将el指向的元素template放置内容;执行mounted钩子函数模板已经编译完成,开始挂载,函数执行后页面显示;DOM已经生成;对当前内容更改,执行beforeUpdate钩子函数组件更新之前,需要调用的钩子函数;执行updated钩子函数组件更新之后,页面已经是展示后的效果,对当前页面发生一些改变使用该函数;属性变化结束之后,进入组件实例化对象的生命周期尾部,在销毁之前调用beforeDestroy;销毁之后调用destroyed
Header.vue

<template>
  <header v-on:click="changTitle">
    <h1>{{title1}}{{title}}</h1>
  </header>
</template>

<script>

export default {
  name:'app-header',
  props:{
    title:{
      type:String
    }
  },
  data(){
    return{
      title1:"Vue.js Demo"
    }
  },
  methods:{
    changTitle:function(){
      //this.title = "changed";
      this.$emit("titleChanged","子向父组件传值");
    }
  },
  beforeCreate:function(){
    alert("组件实例化之前执行的函数");
  },
  created:function(){
    alert("组件实例化完毕,但页面还未显示");
  },
  beforeMount:function(){
    alert("组件挂载前,页面仍未展示,但虚拟Dom已经配置");
  },
  mounted:function(){
    alert("组件挂载后,此方法执行后,页面显示");
  },
  beforeUpdate:function(){
    alert("组件更新前,页面仍未更新,但虚拟Dom已经配置");
  },
  updated:function(){
    alert("组件更新,此方法执行后,页面显示");
  },
  beforeDestory:function(){
    alert("组件销毁前");
  },
  destoryed:function(){
    alert("组件销毁");
  }

}
</script>

<style scoped>
header{
    background: hotpink;
    padding: 10px;
}

h1{
    color: #eee;
    text-align: center;
}
</style>

路由

网络页面与页面之间的跳转,路由的性能优化的更好。使用路由机制不会实现请求与页面刷新,直接跳转

1.使用npm命令npm install npm vue-router –save-dev 安装路由模块

2.引入import VueRouter from 'vue-router'路由模块

3.使用Vue.use(VueRouter)中间件使用路由并配置,需要传递对象,routers对象有path根路径,调用component跳转对应地址

4.使用a标签去实现跳转的话,每次跳转都会重新加载一次页面,影响性能。使用router-link to标签实现功能
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 VueRouter from 'vue-router'
import App from './App'
import HelloWorld from './components/HelloWorld'
import Home from './components/Home'
// import Users from './components/Users'

Vue.config.productionTip = false
Vue.use(VueRouter)

//配置路由
const router = new VueRouter({
    routes:[
        {path:"/",component:Home},
        {path:"/helloworld",component:HelloWorld},
    ],
    mode:"history"
})

// 注册全局组件
// Vue.component("users",Users)

/* eslint-disable no-new */
new Vue({
  router,
  el: '#app',
  template: '<App/>',
  components: { App }
})

/* index.html: 整个项目的入口文件  
 * main.js: 整个项目的逻辑主文件  
 * Vue实例: vue的实例化对象
   包含: el / tem / com  
 * temp: 模板中可以写html / 调用其他组件  
 * <App/>:
   代表模板要执行的组件文件,跟App.vue中的name属性有关  
 * comp:
   组件组中要包含需要调用的组件名,例如上面模板调用了<App/>,那么组件组中就一定要包含App组件  
 * import:
   import用于导入需要依赖的文件,例如上方组件组中,
   想要引入App组件,那么首先要使用import引入这个组件文件  
 * import .. from ..: import 后面是自己起的名字,from后面是组件的名字
 */

App.vue

<template>
  <div id="app">
  <ul>
    <li><router-link to="/">Home</router-link></li>
    <li><router-link to="/helloworld">Hello</router-link></li>
  </ul>
  <router-view></router-view>
  </div>
</template>

<script>

export default {
  name: 'app',
  data(){
    return {

    }
  }
}
</script>

<style scoped>

</style>

HTTP请求

Vue自带的HTTP请求vue-resource

1.使用npm install vue-resource -–save-dev安装vue-resource模块

2.在main.js中导入import VueResource from 'vue-resource'
Vue.use(VueResource)并使用

3.在页面加载之前使用created方法获取http请求在数据做AJAX练习的网站http://jsonplaceholder.typicode.com/用户数据实现

Home.vue

<template>
  <div id="home">
    <app-header v-on:titleChanged="updateTitle($event)" v-bind:title="title"></app-header>
    <app-users v-bind:users="users"></app-users>
    <app-users v-bind:users="users"></app-users>
    <app-footer v-bind:title="title"></app-footer>
  </div>
</template>

<script>
import Header from './Header'
import Footer from './Footer'
import Users from './Users'
export default {
  name: 'home',
  components:{
    "app-header":Header,
    "app-footer":Footer,
    "app-users":Users
  },
  data(){
    return{
      // title:"这是我的第一个VUe脚手架项目!"
      users:[
      // {name:"Lawson",position:"Web开发",show:false},
      // {name:"Aalto",position:"Java开发",show:false},
      // {name:"Pearl",position:"php开发",show:false},
      // {name:"Mabel",position:"Python开发",show:false},
      // {name:"Appleseed",position:"C++开发",show:false},
      // {name:"Hadley",position:"Android开发",show:false},
      // {name:"Nance",position:"Ios开发",show:false}
    ],
    title:"传递的一个值(number string boolean)"
    }
  },
  methods:{
    updateTitle(title){
      this.title = title;
    }
  },
  created(){
    this.$http.get("http://jsonplaceholder.typicode.com/users").then((data) => {
    //  console.log(data);
    this.users = data.body;
    })
  }
}
</script>

<style scoped>

</style>
  • 0
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

极客范儿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值