说明:实际上你什么都不用安装,因为它就是普通的JS库而已
image.png
后文的不少代码可以直接嵌套进下面的代码块做实验:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>测试Vue</title>
<!--script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script-->
<script src="https://unpkg.com/vue"></script>
</head>
<body>
<div id="app">
<p>{{ message }}</p>
</div>
<script>
new Vue({
el: '#app',
data: {
message: 'Hello Vue.js! 你实际就是普通的js'
}
})
</script>
</body>
</html>
但是这样毕竟太原始了,我们从工程角度出发考虑它的使用,这就需要安装一些东西
1. Vue安装
可以借鉴https://baijiahao.baidu.com/s?id=1621989444415819861&wfr=spider&for=pc
1.1 Node安装
注意,不需要手工配置PATH
配置nmp代理:
C:\Users\13770940779>npm config set registry https://registry.npm.taobao.org
1.2 安装Vue
1.2.1 全局模式安装脚手架工具vue-cli
C:\Users\13770940779>npm install --global vue-cli
1.2.2 安装webpack
C:\Users\13770940779>npm install -g webpack
1.2.3 Vue项目初始化
D:\vueproject\test1>vue init webpack myVue
1.2.4 使用npm install 安装package.json包中的依赖
d:\vueproject\test1\myVue>npm install
1.2.5 运行项目
d:\vueproject\test1\myVue>npm run dev
提示:有时候我们想使用vue create getting-to-know-vue命令,但是发现vue cli版本过低,于是执行npm install -g @vue/cli,但是有可能会出错,比如提示诸如not permit这样的提示。此时你可以需要升级npm,使用npm install -g npm@latest,执行完毕后再执行npm install -g @vue/cli就能成功
1.2.6 npm create XX生成的main.js的介绍
主要介绍一下el和template属性的作用。实际上你要结合传统的DOM API等效代码来看才有意义
2. 简单的语法知识
2.1 Vue directive(指令)和interpolation(插入)两种使用方式
2.1.1 简单的directive
A. v-if
注意:
1. The v-else directive is applied immediately after v-if
2.v-else-if的使用:image.png
3.template 元素的使用:image.png
image.png
B. v-show
如果元素的显示和隐藏会进行很多次,则v-show可能就会有性能优势,因为它只需要在初始化的时候加载一次
C 循环指令v-for
解释一下v-bind:key的作用:image.png
如何实现表格行明暗相间效果:
<template>
<div class="container-fluid">
<h2 class="bg-primary text-white text-center p-3">Products</h2>
<table class="table table-sm table-bordered text-left">
<tr><th>Index</th><th>Name</th><th>Price</th></tr>
<tbody>
<tr v-for="(p, i) in products"
v-bind:key="p.name" v-bind:odd2="i % 2 == 0">
<td>{{ i + 1 }}</td>
<td>{{ p.name }}</td>
<td>{{ p.price | currency }}</td>
</tr>
</tbody>
</table>
<div class="text-center"><button v-on:click="handleClick" class="btn btn-primary">Press Me</button>
</div>
</div>
</template>
<script>
export default {
name: "MyComponent",
data: function () {
return {
products: [{ name: "Kayak", price: 275 },{ name: "Lifejacket", price: 48.95 },{ name: "Soccer Ball", price: 19.50 },
{ name: "Corner Flags", price: 39.95 },{ name: "Stadium", price: 79500 }, { name: "Thinking Cap", price: 16 }
]
}
},
filters: {
currency(value) {
return new Intl.NumberFormat("en-US",{ style: "currency", currency: "USD", }).format(value);
},
},
methods: {
handleClick() {this.products.push(this.products.shift());}
}
}
</script>
<style>
tbody > tr:nth-child(even) { background-color: coral; }
tbody > tr:nth-child(odd) { background-color: lightblue; }
</style>
或者用下面这个方法:<template>
<div class="container-fluid">
<h2 class="bg-primary text-white text-center p-3">Products</h2>
<table class="table table-sm table-bordered text-left">
<tr><th>Index</th><th>key</th><th>Value.Name</th><th>Value.Price</th></tr>
<tbody>
<!--注意对于key-val结构首先是value 然后才是key-->
<tr v-for="(p, key, i) in products" v-bind:key="p.name">
<td>{{ i + 1 }}</td>
<td>{{ key}}</td>
<td>{{ p.name }}</td>
<td>{{ p.price | currency }}</td>
</tr>
</tbody>
</table>
<div class="text-center"><button v-on:click="handleClick" class="btn btn-primary">Press Me</button></div>
</div>
</template>
<script>
import Vue from "vue";
export default {
name: "MyComponent",
data: function () {
return {
products: {
1: { name: "Kayak", price: 275 },
"啥2": { name: "Lifejacket", price: 48.95 },
"某3": { name: "Soccer Ball", price: 19.50 },
4: { name: "Corner Flags", price: 39.95 }
}
}
},
filters: {currency(value) {return new Intl.NumberFormat("en-US",{ style: "currency", currency: "USD", }).format(value);
},
},
methods: {
handleClick() {
Vue.set(this.products, 5, { name: "Running Shoes", price: 100});
}
}
}
</script>
<style>
[odd] { background-color: coral; }
</style>
D 绑定参数v-bind
E v-model双向绑定数据
<div id ="ww">
<p>FullName: {{fullName}}</p>
<input type="text" v-model="fullName"><p/>
<input type="text" v-model:value="fullName"><p/>
<input v-bind:value="fullName" v-on:input="fullName = $event.target.value"/>
</div>
<script>
new Vue({
el: '#ww',
data: {
firstName: 'Dawei',
lastName: 'Lou',
fullName: ''
}
})
</script>
F v-on事件绑定
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>测试Vue</title>
<script src="D:\softwareback\web\vue.min.js"></script>
<script src="filter.js"></script>
</head>
<body>
<!--displaying data -- interactive-->
<!--event binding in Vue-->
<div id="app">
<button v-on:click="counter++">Click to increase counter</button>
<p>You've clicked the button {{ counter }}</p> times.
</div>
<div id="app2">
<button v-on:click="increase">Click to increase counter</button>
<p>You've clicked the button {{ counter }}</p> times.
</div>
<script>
new Vue({
el: '#app2',
data: {
counter: 0
},
methods: {
increase(e) {
this.counter++;
}
}
});
</script>
</body>
</html>
还有诸如v-on:input
G v-html 动态设置HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>测试Vue</title>
<script src="D:\softwareback\web\vue.min.js"></script>
</head>
<body>
<div id="app">
<!-- {}}/v-text不能解析html元素,只会照样输出 -->
<p>{{hello}}</p>
<p v-text = 'hello'></p>
<p v-html = 'hello'></p>
</div>
</body>
<script>
new Vue({
el:'#app',
data:{
hello:'<span>hello world</span>'
}
})
</script>
</html>
再看一个例子(这个例子使用的是vue cli建立的工程):
H 使用例子
2.1.2 interpolation相关
2.1.3 Directive高级话题
2.1.3.1 设置一个Element的 Attributes 和 Properties
A 使用对象配置classes
APP.vue:
<template>
<div class="container-fluid text-center">
<div class="bg-primary text-white m-2 p-3">
<h3 v-bind:class="elemClasses" class="display-4">Product: {{name}}</h3>
</div>
<button v-on:click="handleClick" class="btn btn-primary">
Press Me
</button>
<button v-on:click="handleOtherClick" class="btn btn-primary">
Or Press Me
</button>
</div>
</template>
<script>
export default {
name: "MyComponent",
data: function () {
return {
name: "Lifejacket",
highlight1: false,
highlight2: false
}
},
computed: {
elemClasses() {
return {
"text-dark": this.highlight1,
"bg-light": this.highlight2
}
}
},
methods: {
handleClick() {
this.highlight1 = !this.highlight1;
},
handleOtherClick() {
this.highlight2 = !this.highlight2;
}
}
}
</script>
B 设置个别的style
C 设置个别的style
<template>
<div class="container-fluid text-center">
<div class="bg-primary text-white m-2 p-3">
<h3 v-bind:style="elemStyles" class="display-4">Product: {{name}}</h3>
</div>
<button v-on:click="handleClick" class="btn btn-primary">
Press Me
</button>
</div>
</template>
<script>
export default {
name: "MyComponent",
data: function () {
return {
name: "Lifejacket",
highlight: false,
}
},
computed: {
elemStyles() {
return {
"border":"5px solid red",
"background-color":this.highlight ? "coral": "",
}
}
},
methods: {handleClick() {this.highlight = !this.highlight;} }
}
</script>
D 设置其他Attribute
<template>
<div class="container-fluid text-center">
<div class="bg-primary text-white m-2 p-3">
<h3 v-bind:data-size="size" class="display-4">Product: {{name}}</h3>
</div>
<button v-on:click="handleClick" class="btn btn-primary">Press Me</button>
</div>
</template>
<script>
export default {
name: "MyComponent",
data: function () {
return {
name: "Lifejacket",
highlight: false,
}
},
computed: {
size() {
return this.highlight ? "big" : "small";
}
},
methods: {
handleClick() {this.highlight = !this.highlight;}
}
}
</script>
<style>
[data-size=big] { font-size: 40pt; }
[data-size=small] { font-size: 20pt; }
</style>
E 设置多个Attributes
<template>
<div class="container-fluid text-center">
<div class="bg-primary text-white m-2 p-3">
<h3 v-bind="attrValues">Product: {{name}}</h3>
</div>
<button v-on:click="handleClick" class="btn btn-primary">Press Me</button>
</div>
</template>
<script>
export default {
name: "MyComponent",
data: function () {
return {
name: "Lifejacket",
highlight: false,
}
},
computed: {
attrValues() {
return {
class: this.highlight ? ["bg-light", "text-dark"] : [],
style: {border: this.highlight ? "5px solid red": ""},
"data-size": this.highlight ? "big" : "small"
}
}
},
methods: {
handleClick() {this.highlight = !this.highlight;}
}
}
</script>
<style>
[data-size=big] { font-size: 40pt; }
[data-size=small] { font-size: 20pt; }
</style>
F 设置多个Attributes
2.2 Data的类型示例
3. Reactivity响应式编程
Vue 会观察数据对象,一旦发现改变了,则会更新DOM
4. 定义函数
4.1 函数的定义和使用
<script>
new Vue({
el: '#app',
data: {
status: 2
},
methods: {
statusFromId(id) {
const status = ({
0: 'Asleep',
1: 'Eating',
2: 'Learning Vue'
})[id];
return status || 'Unknown status: ' + id;
}
}
});
</script>
4.2 method中的this
5. Computed Properties
你可以向访问普通data object的property一样访问它,但是它的定义像是一个函数:
另外一种使用方法:
<div id="app">
<p>numbers is : {{numbers}}, and sum of numbers: {{ numberTotal }}</p>
</div>
<script>
var m = new Vue({
el: '#app',
data: {
numbers: [5, 8, 3]
},
computed: {
numberTotal: {
get() {
return this.numbers.reduce((sum, val) => sum + val);
},
set(newValue) {
const oldValue = this.numberTotal;
const difference = newValue - oldValue;
this.numbers.push(difference)
}
}
}
});
m.numberTotal += 5;
</script>
我们实际也可以试试响应式编程,如下修改diam:
<div id="app">
<p>numbers is : {{numbers}}, and sum of numbers: {{ numberTotal }}</p>
</div>
<script>
var m = new Vue({
el: '#app',
data: {
numbers: [5, 8, 3]
},
computed: {
numberTotal: {
get() {
return this.numbers.reduce((sum, val) => sum + val);
},
set(newValue) {
const oldValue = this.numberTotal;
const difference = newValue - oldValue;
this.numbers.push(difference)
}
}
}
});
//循环8次,每次增加一个5, 然后你可以观察浏览器的数据自动更新效果
addNumberEveryOneMinutesWithTimes(5, 8);
function addNumberEveryOneMinutesWithTimes(v, times)
{
var count=0;
var t = setInterval(function()
{
count++;
console.log(count);
m.numberTotal += v;
if (count > times)
{
clearInterval(t);
}
}, 1000 );
}
</script>
6. Watchers(用于完成异步操作)
6.1 常见模式
下面这个例子你会看到下面的效果:如果你修改文本框中内容,几秒后你会看到其下显示内容会显示5秒前用户输入的内容
<div id="app">
<input type="text" v-model="inputValue"/>
<p>Five seconds ago, the input said "{{ oldInputValue }}".</p>
</div>
<script>
new Vue({
el: '#app',
data: {
inputValue: '',
oldInputValue: ''
},
watch: {
inputValue() {
const newValue = this.inputValue;
setTimeout(() => {
this.oldInputValue = newValue;
console.log("上一次的值是:"+this.oldInputValue);
}, 5000);
}
}
});
</script>
解释如下:
6.2 Watching Data Object里面的对象的自己的属性
<div id="app">
<input type="text" v-model="formData.inputValue"/>
<p>Five seconds ago, the input said "{{ formData.oldInputValue }}".</p>
</div>
<script>
new Vue({
el: '#app',
data: {
formData:
{
inputValue: '',
oldInputValue:''
}
},
watch: {
'formData.inputValue'() {
const newValue = this.formData.inputValue;
setTimeout(() => {
this.formData.oldInputValue = newValue;
console.log("采用嵌套方式,上一次的值是:"+this.formData.oldInputValue);
}, 5000);
}
}
});
</script>
6.3 Getting the Old Value更简单的方法
<div id="app">
<input type="text" v-model="formData.inputValue"/>
</div>
<script>
new Vue({
el: '#app',
data: {
formData:
{
inputValue: ''
}
},
watch: {
'formData.inputValue'(newVal, oldVal) {
console.log("值变化方式为:"+newVal+"<--"+oldVal);
}
}
});
</script>
6.4 Watch中handler的使用
演示一下deep:true的用法:
<div id='root'>
<p>obj.a: {{obj.a}}</p>
<p>obj.a: <input type="text" v-model="obj.a"></p>
</div>
<script type="text/javascript">
new Vue({
el: '#root',
data: {
obj: {
a: 123
}
},
watch: {
obj: {
handler(newName, oldName) {
console.log('obj.a changed');
},
immediate: true,
deep: true
}
}
})
</script>
6.5 filter的写法
也可以在new Vue的外面定义一个全局filter:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>测试Vue</title>
<!--script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script-->
<!--script src="https://unpkg.com/vue"></script-->
<script src="D:\softwareback\web\vue.min.js"></script>
<script src="filter.js"></script>
</head>
<body>
<div id="app">
<p>Product one cost: {{ productOneCost | formatDollarsCost | addBracket }}</p>
<p>Product two cost: {{ productTwoCost | formatDollarsCost }}</p>
<p>Product three cost: {{ productThreeCost | formatCost('¥') }}</p>
<input type="text" v-bind:value="productOneCost | formatCost('¥')"/>
<p>Product three cost: {{ productThreeCost | formatCost2('$') }}</p>
<input type="text" v-bind:value="productOneCost | formatCost3('$')"/>
</div>
<script>
Vue.filter("formatCost2", function (value, prefix)
{
return prefix + (value / 100).toFixed(2);
});
new Vue({
el: '#app',
data: {
productOneCost: 998,
productTwoCost: 2399,
productThreeCost: 5300
},
filters: {
formatDollarsCost(value) {
return '$' + (value / 100).toFixed(2);
},
addBracket(value){
return '('+value+')';
},
formatCost(value, symbol){
return symbol+(value / 100).toFixed(2);
}
}
});
</script>
</body>
</html>
7 JS中通过ref引用element
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>测试Vue</title>
<!--script src="https://cdn.staticfile.org/vue/2.2.2/vue.min.js"></script-->
<script src="vue.min.js"></script>
</head>
<body>
<div id="app">
<input type = "text" ref="input1" id="input1id"/>
<button @click="add">添加</button>
</div>
<script>
new Vue({
el: '#app',
methods: {
add: function()
{
this.$refs.input1.value="22";
console.log(this.$refs.input1);
console.log(document.getElementById("input1id"));
}
}
})
</script>
</body>
</html>
8 Inputs 和 Events
8.1鼠标点击事件例子
前面给过一个例子,这里再展示一下:<div id="app">
<button v-on:click="counter++">Click to increase counter</button>
<p>You've clicked the button {{ counter }}</p> times.
</div>
<div id="app2">
<button v-on:click="increase">Click to increase counter</button>
<p>You've clicked the button {{ counter }}</p> times.
</div>
<script>
new Vue({
el: '#app2',
data: {
counter: 0
},
methods: {
increase(e) {
this.counter++;
}
}
});
</script>
8.2 键盘事件例子(v-on)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>测试Vue</title>
<script src="D:\softwareback\web\vue.min.js"></script>
</head>
<body>
<!--displaying data -- interactive-->
<!--event binding in Vue-->
<div id="app">
<input @keyup="handleKeyup"/>监听所有</input><p/>
<input v-on:keyup="handleKeyup"/>监听所有</input><p/>
<input v-on:keyup.enter="handleKeyup"/>只监听enter</input><p/>
<input @keyup.enter="handleKeyup"/>只监听enter</input><p/>
<input v-on:keyup.tab="handleKeyup">只监听tab事件</input></p>
<input v-on:keyup.f1="handleKeyup">只监听F1事件</input></p>
<input v-on:keyup.27="handleKeyup">只监听keyCode为27的事件</input></p>
<!-- Alt + C -->
<input @keyup.alt.67="handleKeyup">只监听Alt + C事件</input><p/>
<!-- Ctrl + Click -->
<input @click.ctrl="handleKeyup">只监听Ctrl + 鼠标Click事件</input>
</div>
<script>
new Vue({
el: '#app',
methods: {
handleKeyup(e) {
console.log("监听到一个事件"+e.keyCode);
if (e.keyCode == 27) {
console.log("Escape按下了")
}
}
}
});
</script>
</body>
</html>
9. 声明周期管理
<div id="app">
<p>{{ number }}</p>
<input type="text" name="btnSetNumber" v-model="number">
</div>
<script>
var app = new Vue({
el: '#app',
data: {number: 1},
beforeCreate: function () {
console.log('beforeCreate 钩子执行...');
console.log(this.number)//undefined
},
created: function () {
console.log('cteated 钩子执行...');
console.log(this.number)//1
},
beforeMount: function () {
console.log('beforeMount 钩子执行...');
console.log(this.number)},
mounted: function () {
console.log('mounted 钩子执行...');
console.log(this.number)},
beforeUpdate: function () {
console.log('beforeUpdate 钩子执行...');
console.log(this.number)
},
updated: function () {
console.log('updated 钩子执行...');
console.log(this.number)
},
beforeDestroy: function () {
console.log('beforeDestroy 钩子执行...');
console.log(this.number)
},
destroyed: function () {
console.log('destroyed 钩子执行...');
console.log(this.number)
}
});
</script>
10. 自定义directive(指令)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>测试Vue</title>
<script src="D:\softwareback\web\vue.min.js"></script>
</head>
<body>
<p> 这一行不刷新 </p>
<div id="app">
<p v-likeif:myparam.mymodifiera="3000">This content will blink</p>
</div>
</body>
<script>
Vue.directive('likeif', {
bind(el, binding) {
let isVisible = true;
setInterval(() => {
isVisible = !isVisible;
el.style.visibility = isVisible ? 'visible' : 'hidden';
}, binding.value || 1000);
var s = JSON.stringify
el.innerHTML =
'name: ' + s(binding.name) + '<br/>' +
'value: ' + s(binding.value) + '<br/>' +
'expression: ' + s(binding.expression) + '<br/>' +
'argument: ' + s(binding.arg) + '<br/>' +
'modifiers: ' + s(binding.modifiers) + '<br/>';
console.log("名称是: "+s(binding.name));
console.log("参数是: "+s(binding.arg));
console.log("修饰符是: "+s(binding.modifiers));
console.log("值是: "+s(binding.value));
}
});
new Vue({
el:'#app'
})
</script>
</html>
11. Transitions和 Animations
CSS Transitions
<div id="app">
<button @click="divVisible = !divVisible">Toggle visibility</button>
<transition name="fade">
<div v-if="divVisible">This content is sometimes hidden</div>
</transition>
</div>
<script>
new Vue({
el: '#app',
data: {
divVisible: true
}
});
</script>
<style type="text/css">
.fade-enter-active, .fade-leave-active {
transition: opacity .5s;
}
.fade-enter, .fade-leave-to {
opacity: 0;
}
</style>
JavaScript Animations
这里后面再找个例子