官网:
MVVM
模式永远的 HelloWord
编码:
<div id="app">
<input type="text" v-model="username" />
<p>Hello, {{username}}</p>
</div>
<script src="../js/vue.js"></script>
<script type="text/javascript">
new Vue({
// 配置对象: 属性名是一些特定的名称
el: "#app", // 值是选择器 element 用来查找跟元素
data: {
username: "OY_test", // 包含多个可变数据的对象,相当于state,为模板页面提供数据
},
});
</script>
效果示例:
Vue 的 MVVM
模板的理解
{{}}`) - 指令(以 v-开头的自定义标签属性) ### 1、双大括号表达式 - **语法:** `{{exp}}
v-on:keyup='xxx' v-on:keyup='xxx'(参数) v-on:keyup.enter='xxx'
@keyup='xxx' @keyup.enter='xxx'
<div id="app">
<h2>1. 双大括号表达式</h2>
<p>{{msg}}</p>
<p>{{msg.toUpperCase()}}</p>
<h2>2. 指令一: 强制数据绑定</h2>
<a href="url">访问指定站点</a><br/><!--不能使用-->
<a v-bind:href="url">访问指定站点2</a><br/>
<a :href="url">访问指定站点3</a>
<h2>3. 指令二: 绑定事件监听</h2>
<button v-on:click="handleClick">点我</button>
<button @click="handleClick">点我2</button>
</div>
<script src="../js/vue.js"></script>
<script type="text/javascript">
new Vue({
el: "#app",
data: {
msg: "NBA I Like This Game!",
url: "http://www.baidu.com",
},
methods: {
handleClick() {
alert("处理点击");
},
},
});
</script>
效果示例:
{{方法名}}
来显示计算的结果<div id="demo">
姓: <input type="text" placeholder="First Name" v-model="firstName"><br>
名: <input type="text" placeholder="Last Name" v-model="lastName"><br>
姓名1(单向): <input type="text" placeholder="Full Name1" v-model="fullName1"><br>
姓名2(单向): <input type="text" placeholder="Full Name2" v-model="fullName2"><br>
姓名3(双向): <input type="text" placeholder="Full Name3" v-model="fullName3"><br>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
var vm = new Vue({
el: "#demo",
data: {
firstName: "Kobe",
lastName: "bryant",
fullName2: "Kobe bryant",
},
computed: {
fullName1: function () {
return this.firstName + " " + this.lastName;
},
fullName3: {
get: function () {
return this.firstName + " " + this.lastName;
},
set: function (value) {
var names = value.split(" ");
this.firstName = names[0];
this.lastName = names[1];
},
},
},
watch: {
lastName: function (newVal, oldVal) {
this.fullName2 = this.firstName + " " + newVal;
},
},
});
vm.$watch("fistName", function (val) {
this.fullName2 = val + " " + this.lastName;
});
</script>
效果示例:
<div id="demo">
<h2>1. class绑定: :class='xxx'</h2>
<p class="classC" :class="Myclass">xxxx</p>
<p :class="{classA: hasA, classB: hasB}">yyyy</p>
<p :class="['classA','classB']">zzz</p>
<h2>2. style绑定</h2>
<p :style="{color: Mycolor, fontSize: mySize + 'px'}">xxxxxxx</p>
<button @click="update">更新</button>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
new Vue({
el: "#demo",
data: {
Myclass: "classA",
hasA: true,
hasB: false,
Mycolor: "red",
mySize: 20,
},
methods: {
update() {
console.log(this);
(this.Myclass = "classB"),
(this.hasA = !this.hasA),
(this.hasB = !this.hasB),
(this.Mycolor = "#ff0000"),
(this.mySize = 30);
},
},
});
</script>
效果示例:
<div id="demo">
<p v-if="ok">表白成功</p>
<p v-else>表白失败</p>
<p v-show="ok">求婚成功</p>
<p v-show="!ok">求婚失败</p>
<button @Click="toggle">切换</button>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
new Vue({
el: "#demo",
data() {
return {
ok: true,
};
},
methods: {
toggle() {
this.ok = !this.ok;
},
},
});
</script>
效果示例:
列表过滤
<div id="demo">
<h2>测试: v-for 遍历数组</h2>
<ul>
<li v-for="(p, index) in persons" :key="p.id">
{{p.id}} -- {{p.name}} -- {{p.age}}
-- <button @click="deleteP(index)">删除</button>
-- <button @click="updateP(index,{id: Date.now(), name: 'Jarry',age: 19})">更新</button>
</li>
</ul>
<h2>测试: v-for 遍历对象</h2>
<ul>
<li v-for="(value, key) in persons[0]" :key="key">
{{key}} = {{value}}
</li>
</ul>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
new Vue({
el: "#demo",
data: {
persons: [
{ id: 1, name: "Tom", age: 15 },
{ id: 2, name: "Jack", age: 12 },
{ id: 4, name: "Bob", age: 17 },
{ id: 6, name: "Rose", age: 16 },
{ id: 8, name: "Else", age: 13 },
],
},
methods: {
deleteP(index) {
this.persons.splice(index, 1);
},
updateP(index, newP) {
// 第一种方式
// this.persons[index].id = newP.id;
// this.Persons[index].name = newP.name;
// this.Persons[index].age = newP.age;
// this.persons[index] = newP // 不会更新界面
this.persons.splice(index, 1, newP); // VUE重写后的splice方法
},
},
});
</script>
效果示例:
列表排序
<div id="app">
<input type="text" v-model="searchName">
<ul>
<li v-for="(p, index) in filterPersons" :key="p.id">
{{p.id}} -- {{p.name}} -- {{p.age}}
</li>
</ul>
<button @click="sortType=2">按年龄升序</button>
<button @click="sortType=3">按年龄降序</button>
<button @click="sortType=1">原本顺序</button>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
new Vue({
el: "#app",
data: {
searchName: "",
sortType: 1, // 排序的类型, 1:不排序, 2:升序, 3: 降序
persons: [
{ id: 1, name: "Tom", age: 15 },
{ id: 2, name: "Jack", age: 12 },
{ id: 4, name: "Bob", age: 17 },
{ id: 6, name: "Rose", age: 16 },
{ id: 8, name: "Else", age: 13 },
],
},
computed: {
filterPersons() {
// 1.得到依赖数据
const { sortType, searchName, persons } = this;
// 2. 进行计算处理,产生结果数据并返回
// 过滤
const arr = persons.filter((p) => p.name.indexOf(searchName) >= 0);
// 进行排序
if (sortType !== 1) {
arr.sort((p1, p2) => {
if (sortType === 2) {
// 升序
return p1.age - p2.age;
} else {
// 降序
return p2.age - p1.age;
}
});
}
return arr;
},
},
});
</script>
效果示例:
<div id="example">
<h2>1. 绑定监听</h2>
<button @click="test1">test1</button>
<button @click="test2('abc')">test2</button>
<button @click="test3('abc',$event)">test3</button>
<h2>2. 事件修饰符</h2>
<!-- 阻止(prevent)事件的默认行为
停止(stop)事件冒泡 -->
<a href="http://oy6090.top" @click.prevent="test4">去学习</a>
<div style="width:200px; height: 200px; background: red;" @click="test5">
<div style="width: 100px; height: 100px; background: blue;" @click.stop="test6"></div>
</div>
<p @clik.once="test6">xxxxx</p>
<h2>3. 按键修饰符</h2>
<input type="text" v-model="msg" @Keyup.13="test7">
<input type="text" v-model="msg" @Keyup.enter="test7">
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
new Vue({
el: '#example',
data: {
msg: ''
},
methods: {
test1(e){
alert(e.target.innerText);
},
test2(value){
alert(value);
},
test3(value,event){
alert(value+"---" + event.target.innerText);
},
test4(event){
//event.preventDefault();
alert('点击了');
},
test5(){
alert('out');
},
test6(){
alert('inner');
},
test7(){
alert(this.msg)
}
}
})
</script>
效果示例:
<div id="demo">
<form action="/xxx" @submit.prevent="register">
<span>用户名: </span>
<input type="text" v-model="user.username"><br>
<span>密码: </span>
<input type="password" v-model="user.pwd"><br>
<span>性别: </span>
<input type="radio" id="female" v-model="user.sex" value="女">
<label for="female">女</label>
<input type="radio" id="male" v-model="user.sex" value="男">
<label for="male">男</label><br>
<span>爱好: </span>
<input type="checkbox" id="basket" v-model="user.likes" value="basket">
<label for="basket">篮球</label>
<input type="checkbox" id="foot" v-model="user.likes" value="foot">
<label for="foot">足球</label>
<input type="checkbox" id="pingpang" v-model="user.likes" value="pingpang">
<label for="pingpang">乒乓</label><br>
<span>城市: </span>
<select v-model="user.cityID">
<option value="">未选择</option>
<option :value="city.id" v-for="(city, index) in allcitys" :key="city.id">{{city.name}}</option>
</select><br>
<span>介绍: </span>
<textarea rows="10" v-model="user.info"></textarea><br><br>
<input type="submit" value="注册">
</form>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
new Vue({
el: "#demo",
data: {
user: {
username: "",
pwd: "",
sex: "女",
likes: ["foot"],
cityID: "1",
info: "",
},
allcitys: [
{ id: 1, name: "HN" },
{ id: 2, name: "SZ" },
{ id: 3, name: "HB" },
],
},
methods: {
register() {
alert("发送注册的ajax请求:" + JSON.stringify(this.user));
},
},
});
</script>
示例效果:
<div id="test">
<button @click="destoryVM">destory vue</button>
<p v-show="isShow" ref="content">Vue 生命周期 {{isShow ? 'show...' : 'hide...'}}</p>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
new Vue({
el: "#test",
data() {
return {
isShow: true,
};
},
beforeCreate() {
console.log("beforeCreate()", this.isShow);
},
// 实现数据代码: 后面可以通过vm 读取data 中的数据
created() {
console.log("created()");
},
// 在第一次显示之后在显示
mounted() {
console.log("mounted()");
this.intervalId = setInterval(() => {
console.log("-----");
this.isShow = !this.isShow;
}, 1000);
},
beforeUpdate() {
// 读取是老的界面
console.log("beforeUpdate()", this.isShow, this.$refs.content.innerHTML);
},
updated() {
console.log("updated()", this.isShow, this.$refs.content.innerHTML);
},
// 销毁之前执行一次
beforeDestroy() {
console.log("beforeDestroy()");
clearInterval(this.intervalId);
},
destroyed() {
console.log("destroyed()");
},
methods: {
destoryVM() {
this.$destroy();
},
},
});
</script>
实例效果:
示例一:
<style type="text/css">
/*过渡样式*/
.move-enter-active,
.move-leave-active {
transition: opacity 5s;
}
/*隐藏时的样式*/
.move-enter,
.move-leave-to {
opacity: 0;
}
/*显示的过渡样式*/
.move2-enter-active {
transition: all 1s;
}
/*隐藏的过渡样式*/
.move2-leave-active {
transition: all 5s;
}
/*隐藏时的样式*/
.move2-enter,
.move2-leave-to {
opacity: 0;
transform: translateX(20px);
}
</style>
<div id="demo">
<button v-on:click="show=!show">
Toggle
</button>
<transition name="move">
<p v-show="show">Hello</p>
</transition>
</div>
<div id="demo2">
<button v-on:click="show=!show">
Toggle2
</button>
<transition name="move2">
<p v-show="show">Hello2</p>
</transition>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
new Vue({
el: "#demo",
data: {
show: true,
},
});
new Vue({
el: "#demo2",
data: {
show: true,
},
});
</script>
效果示例:
示例二:
<style>
/*显示动画样式*/
.bounce-enter-active {
animation: bounce-in 0.5s;
}
.bounce-leave-active {
animation: bounce-in 0.5s reverse;
}
@keyframes bounce-in {
0% {
transform: scale(0);
}
50% {
transform: scale(1.5);
}
100% {
transform: scale(1);
}
}
</style>
<div id="example-2">
<button @click="show = !show">Toggle show</button><br>
<transition name="bounce">
<p v-if="show" style="display: inline-block;">Lorem</p>
</transition>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script>
new Vue({
el: "#example-2",
data: {
show: true,
},
});
</script>
效果示例:
功能: 对要显示的数据进行特定格式化在显示 注意:并没有改变原有的数据,是产生新的对应的数据
Vue.filter(filterName,function(value[arg1,arg2,...])){ // 进行一定的数据处理
return newValue; }
<div>{{myData | filterName}}</div>
<div>{{myData | filterName(arg)}}</div>
<div id="test">
<h2>显示格式化的日期时间</h2>
<p>{{startTime}}</p>
<p>{{startTime | dateFormate}}</p>
<p>{{startTime | dateFormate('YYYY-MM-DD')}}</p>
<p>{{startTime | dateFormate('HH:mm:ss')}}</p>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/moment.js/2.29.1/moment.js"></script>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
// 自定义过滤器
Vue.filter("dateFormate", function (value, formatStr = "YYYY-MM-DD HH:mm:ss") {
//return moment(value).format(formatStr || 'YYYY-MM-DD HH:mm:ss')
return moment(value).format(formatStr);
});
new Vue({
el: "#test",
data() {
return {
startTime: Date.now() - 10000,
};
},
});
</script>
效果示例:
指令 | 描述 |
---|---|
v-text | 更新元素的 textContent |
v-html | 更新元素的 innerHTML |
v-if | 如果为 true, 当前标签才会输出到页面 |
v-else | 如果为 false, 当前标签才会输出到页面 |
v-show | 通过控制 display 样式来控制显示/隐藏 |
v-for | 遍历数组/对象 |
v-on | 绑定事件监听, 一般简写为@ |
v-bind | 强制绑定解析表达式, 可以省略 v-bind |
v-model | 双向数据绑定 |
ref | 指定唯一标识, vue 对象通过$els 属性访问这个元素对象 |
v-cloak | 防止闪现, 与 css 配合: [v-cloak] { display: none } |
Vue.directive('my-directive', function(el, binding){ el.innerHTML =
binding.value.toupperCase() })
directives : { 'my-directive' : { bind (el, binding) { el.innerHTML =
binding.value.toupperCase() } } }
v-my-directive = 'xxx'
内置指令
<div id="example">
<p v-text="msg"></p>
<p v-html="msg"></p>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
new Vue({
el: "#example",
data() {
return {
msg: '<a href="http://oy6090.top">去浏览博客</a>',
};
},
});
</script>
效果示例:
自定义指令
<!--
需求: 自定义2个指令
1. 功能类型于v-text, 但转换为全大写
2. 功能类型于v-text, 但转换为全小写
-->
<div id="test">
<p v-upper-text="msg"></p>
<p v-lower-text="msg"></p>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script type="text/javascript">
// 自定义全局指令
Vue.directive("upper-text", (el, binding) => {
console.log("upper-text", binding);
el.innerText = binding.value.toUpperCase();
});
new Vue({
el: "#test",
data: {
msg: "I will Back!",
},
// 定义局部指令(只对当前vm的模板有效)
directives: {
"lower-text"(el, binding) {
el.innerText = binding.value.toLowerCase();
},
},
});
</script>
效果示例:
说明:
编码示例:
/*
自定义插件
*/
(function () {
const MyPlugin = {};
MyPlugin.install = function (Vue, options) {
// 1.添加全局方法或属性
Vue.myGlobalMethod = function () {
alert("Vue 函数对象方法执行");
};
// 2.添加全局资源
Vue.directive("my-directive", function (el, binding) {
el.innerHTML = "MyPlugin my-directive " + binding.value;
});
// 3.添加实例方法
Vue.prototype.$myMethod = function () {
alert("vue 实例对象方法执行");
};
};
window.MyPlugin = MyPlugin;
})();
<div id="demo">
<!-- 使用自定义指令 -->
<p v-my-directive="msg"></p>
</div>
<script type="text/javascript" src="../js/vue.js"></script>
<script src="vue-myPlugin.js"></script>
<script type="text/javascript">
// 使用自定义插件
Vue.use(MyPlugin);
var vm = new Vue({
el: "#demo",
data: {
msg: "OY_Test",
},
});
// 调用自定义的静态方法
Vue.myGlobalMethod();
// 调用自定义的对象方法
vm.$myMethod();
</script>
效果示例: