英文官网
中文官网
注意区分:js表达式 和 js代码(语句)
表达式:一个表达式会产生一个值,可以放在任何一个需要值的地方:
(1). a(2). a+b(3). demo(1)(4). x === y ? 'a' : 'b'
js代码(语句)
(1). if(){}(2). for(){}
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>初识Vue</title><!-- 引入Vue --><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 准备好一个容器 --><div id="demo"><h1>Hello,{{UpperCase()}},{{address}}</h1></div><script type="text/javascript" &fig.productionTip = false //阻止 vue 在启动时生成生产提示。//创建Vue实例new Vue({el:'#demo', //el用于指定当前Vue实例为哪个容器服务,值通常为css选择器字符串。data:{ //data中用于存储数据,数据供el所指定的容器去使用,值我们暂时先写成一个对象。name:'atguigu',address:'北京'}})</script></body>
</html>
Vue模板语法有2大类:
- 功能:用于解析标签体内容。
- 写法:{{xxx}},xxx是js表达式,且可以直接读取到data中的所有属性。
- 功能:用于解析标签(包括:标签属性、标签体内容、绑定事件…)。
- 举例:v-bind:href=“xxx” 或 简写为 :href=“xxx”,xxx同样要写js表达式,
且可以直接读取到data中的所有属性。
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>模板语法</title><!-- 引入Vue --><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 准备好一个容器--><div id="root"><h1>插值语法</h1><h3>你好,{{name}}</h3><hr/><h1>指令语法</h1><a v-bind:href="UpperCase()" x="hello">点我去{{school.name}}学习1</a><a :href="school.url" x="hello">点我去{{school.name}}学习2</a></div></body><script type="text/javascript"&fig.productionTip = false //阻止 vue 在启动时生成生产提示。new Vue({el:'#root',data:{name:'jack',school:{name:'尚硅谷',url:'',}}})</script>
</html>
Vue中有2种数据绑定的方式:
- 单向绑定(v-bind):数据只能从data流向页面。
- 双向绑定(v-model):数据不仅能从data流向页面,还可以从页面流向
data。
备注:
- 双向绑定一般都应用在表单类元素上(如:input、select等)
- v-model:value 可以简写为 v-model,因为v-model默认收集的就是value值。
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>数据绑定</title><!-- 引入Vue --><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 准备好一个容器--><div id="root"><!-- 普通写法 --><!-- 单向数据绑定:<input type="text" v-bind:value="name"><br/>双向数据绑定:<input type="text" v-model:value="name"><br/> --><!-- 简写 -->单向数据绑定:<input type="text" :value="name"><br/>双向数据绑定:<input type="text" v-model="name"><br/><!-- 如下代码是错误的,因为v-model只能应用在表单类元素(输入类元素)上 --><!-- <h2 v-model:x="name">你好啊</h2> --></div></body><script type="text/javascript"&fig.productionTip = false //阻止 vue 在启动时生成生产提示。new Vue({el:'#root',data:{name:'尚硅谷'}})</script>
</html>
data与el的2种写法:
el有2种写法
(1).new Vue时候配置el属性。
(2).先创建Vue实例,随后再通过vm.$mount(’#root’)指定el的值。
data有2种写法
(1).对象式
(2).函数式
如何选择:目前哪种写法都可以,以后学习到组件时,data必须使用函数式,否则会报错。
一个重要的原则:
由Vue管理的函数,一定不要写箭头函数,一旦写了箭头函数,this就不再是Vue实例了。
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>el与data的两种写法</title><!-- 引入Vue --><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 准备好一个容器--><div id="root"><h1>你好,{{name}}</h1></div></body><script type="text/javascript"&fig.productionTip = false //阻止 vue 在启动时生成生产提示。//el的两种写法/* const v = new Vue({//el:'#root', //第一种写法data:{name:'尚硅谷'}})console.log(v)v.$mount('#root') //第二种写法 *///data的两种写法new Vue({el:'#root',//data的第一种写法:对象式/* data:{name:'尚硅谷'} *///data的第二种写法:函数式data(){console.log('@@@',this) //此处的this是Vue实例对象return{name:'尚硅谷'}}})</script>
</html>
MVVM模型介绍:
观察发现:
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>理解MVVM</title><!-- 引入Vue --><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 准备好一个容器--><div id="root"><h1>学校名称:{{name}}</h1><h1>学校地址:{{address}}</h1><!-- <h1>测试一下1:{{1+1}}</h1><h1>测试一下2:{{$options}}</h1><h1>测试一下3:{{$emit}}</h1><h1>测试一下4:{{_c}}</h1> --></div></body><script type="text/javascript"&fig.productionTip = false //阻止 vue 在启动时生成生产提示。const vm = new Vue({el:'#root',data:{name:'尚硅谷',address:'北京',}})console.log(vm)</script>
</html>
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>回顾Object.defineproperty方法</title></head><body><script type="text/javascript" >let number = 18let person = {name:'张三',sex:'男',}Object.defineProperty(person,'age',{// value:18,// enumerable:true, //控制属性是否可以枚举,默认值是false// writable:true, //控制属性是否可以被修改,默认值是false// configurable:true //控制属性是否可以被删除,默认值是false//当有人读取person的age属性时,get函数(getter)就会被调用,且返回值就是age的值get(){console.log('有人读取age属性了')return number},//当有人修改person的age属性时,set函数(setter)就会被调用,且会收到修改的具体值set(value){console.log('有人修改了age属性,且值是',value)number = value}})// console.log(Object.keys(person))console.log(person)</script></body>
</html>
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>何为数据代理</title></head><body><!-- 数据代理:通过一个对象代理对另一个对象中属性的操作(读/写)--><script type="text/javascript" >let obj = {x:100}let obj2 = {y:200}Object.defineProperty(obj2,'x',{get(){return obj.x},set(value){obj.x = value}})</script></body>
</html>
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>Vue中的数据代理</title><!-- 引入Vue --><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 准备好一个容器--><div id="root"><h2>学校名称:{{name}}</h2><h2>学校地址:{{address}}</h2></div></body><script type="text/javascript"&fig.productionTip = false //阻止 vue 在启动时生成生产提示。const vm = new Vue({el:'#root',data:{name:'尚硅谷',address:'宏福科技园'}})</script>
</html>
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>事件的基本使用</title><!-- 引入Vue --><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 准备好一个容器--><div id="root"><h2>欢迎来到{{name}}学习</h2><!-- <button v-on:click="showInfo">点我提示信息</button> --><button @click="showInfo1">点我提示信息1(不传参)</button><button @click="showInfo2($event,66)">点我提示信息2(传参)</button></div></body><script type="text/javascript"&fig.productionTip = false //阻止 vue 在启动时生成生产提示。const vm = new Vue({el:'#root',data:{name:'尚硅谷',},methods:{showInfo1(event){// console.log(event.target.innerText)// console.log(this) //此处的this是vmalert('同学你好!')},showInfo2(event,number){console.log(event,number)// console.log(event.target.innerText)// console.log(this) //此处的this是vmalert('同学你好!!')}}})</script>
</html>
Vue中的事件修饰符:
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>事件修饰符</title><!-- 引入Vue --><script type="text/javascript" src="../js/vue.js"></script><style>*{margin-top: 20px;}.demo1{height: 50px;background-color: skyblue;}.box1{padding: 5px;background-color: skyblue;}.box2{padding: 5px;background-color: orange;}.list{width: 200px;height: 200px;background-color: peru;overflow: auto;}li{height: 100px;}</style></head><body><!-- 准备好一个容器--><div id="root"><h2>欢迎来到{{name}}学习</h2><!-- 阻止默认事件(常用) --><a href="" @click.prevent="showInfo">点我提示信息</a><!-- 阻止事件冒泡(常用) --><div class="demo1" @click="showInfo"><button @click.stop="showInfo">点我提示信息</button><!-- 修饰符可以连续写 --><!-- <a href="" @click.prevent.stop="showInfo">点我提示信息</a> --></div><!-- 事件只触发一次(常用) --><button ="showInfo">点我提示信息</button><!-- 使用事件的捕获模式 --><div class="box1" @click.capture="showMsg(1)">div1<div class="box2" @click="showMsg(2)">div2</div></div><!-- 只有event.target是当前操作的元素时才触发事件; --><div class="demo1" @click.self="showInfo"><button @click="showInfo">点我提示信息</button></div><!-- 事件的默认行为立即执行,无需等待事件回调执行完毕; --><ul @wheel.passive="demo" class="list"><li>1</li><li>2</li><li>3</li><li>4</li></ul></div></body><script type="text/javascript"&fig.productionTip = false //阻止 vue 在启动时生成生产提示。new Vue({el:'#root',data:{name:'尚硅谷'},methods:{showInfo(e){alert('同学你好!')// console.log(e.target)},showMsg(msg){console.log(msg)},demo(){for (let i = 0; i < 100000; i++) {console.log('#')}console.log('累坏了')}}})</script>
</html>
Vue中常用的按键别名:
回车 => enter删除 => delete (捕获“删除”和“退格”键)退出 => esc空格 => space换行 => tab (特殊,必须配合keydown去使用)上 => up下 => down左 => left右 => right
Vue未提供别名的按键,可以使用按键原始的key值去绑定,但注意要转为kebab-case(短横线命名)
系统修饰键(用法特殊):ctrl、alt、shift、meta
(1).配合keyup使用:按下修饰键的同时,再按下其他键,随后释放其他键,事件才被触发。
(2).配合keydown使用:正常触发事件。
也可以使用keyCode去指定具体的按键(不推荐)
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>键盘事件</title><!-- 引入Vue --><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 准备好一个容器--><div id="root"><h2>欢迎来到{{name}}学习</h2><input type="text" placeholder="按下回车提示输入" @keydown.huiche="showInfo"></div></body><script type="text/javascript"&fig.productionTip = false //阻止 vue 在启动时生成生产提示。fig.keyCodes.huiche = 13 //定义了一个别名按键new Vue({el:'#root',data:{name:'尚硅谷'},methods: {showInfo(e){// console.log(e.key,e.keyCode)console.log(e.target.value)}},})</script>
</html>
定义:
要用的属性不存在,要通过已有属性计算得来。
原理:
底层借助了Objcet.defineproperty方法提供的getter和setter。
get函数什么时候执行?
优势:
与methods实现相比,内部有缓存机制(复用),效率更高,调试方便。
备注:
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>姓名案例_计算属性实现</title><!-- 引入Vue --><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 准备好一个容器--><div id="root">姓:<input type="text" v-model="firstName"> <br/><br/>名:<input type="text" v-model="lastName"> <br/><br/>测试:<input type="text" v-model="x"> <br/><br/>全名:<span>{{fullName}}</span> <br/><br/><!-- 全名:<span>{{fullName}}</span> <br/><br/>全名:<span>{{fullName}}</span> <br/><br/>全名:<span>{{fullName}}</span> --></div></body><script type="text/javascript"&fig.productionTip = false //阻止 vue 在启动时生成生产提示。const vm = new Vue({el:'#root',data:{firstName:'张',lastName:'三',x:'你好'},methods: {demo(){}},computed:{fullName:{//get有什么作用?当有人读取fullName时,get就会被调用,且返回值就作为fullName的值//get什么时候调用?1.初次读取fullName时。2.所依赖的数据发生变化时。get(){console.log('get被调用了')// console.log(this) //此处的this是vmreturn this.firstName + '-' + this.lastName},//set什么时候调用? 当fullName被修改时。set(value){console.log('set',value)const arr = value.split('-')this.firstName = arr[0]this.lastName = arr[1]}}}})</script>
</html>
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>姓名案例_计算属性实现</title><!-- 引入Vue --><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 准备好一个容器--><div id="root">姓:<input type="text" v-model="firstName"> <br/><br/>名:<input type="text" v-model="lastName"> <br/><br/>全名:<span>{{fullName}}</span> <br/><br/></div></body><script type="text/javascript"&fig.productionTip = false //阻止 vue 在启动时生成生产提示。const vm = new Vue({el:'#root',data:{firstName:'张',lastName:'三',},computed:{//完整写法/* fullName:{get(){console.log('get被调用了')return this.firstName + '-' + this.lastName},set(value){console.log('set',value)const arr = value.split('-')this.firstName = arr[0]this.lastName = arr[1]}} *///简写fullName(){console.log('get被调用了')return this.firstName + '-' + this.lastName}}})</script>
</html>
computed和watch之间的区别:
两个重要的小原则:
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>天气案例_监视属性</title><!-- 引入Vue --><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 监视属性watch:1.当被监视的属性变化时, 回调函数自动调用, 进行相关操作2.监视的属性必须存在,才能进行监视!!3.监视的两种写法:(1).new Vue时传入watch配置(2).通过vm.$watch监视--><!-- 准备好一个容器--><div id="root"><h2>今天天气很{{info}}</h2><button @click="changeWeather">切换天气</button></div></body><script type="text/javascript"&fig.productionTip = false //阻止 vue 在启动时生成生产提示。const vm = new Vue({el:'#root',data:{isHot:true,},computed:{info(){return this.isHot ? '炎热' : '凉爽'}},methods: {changeWeather(){this.isHot = !this.isHot}},/* watch:{isHot:{immediate:true, //初始化时让handler调用一下//handler什么时候调用?当isHot发生改变时。handler(newValue,oldValue){console.log('isHot被修改了',newValue,oldValue)}}} */})vm.$watch('isHot',{immediate:true, //初始化时让handler调用一下//handler什么时候调用?当isHot发生改变时。handler(newValue,oldValue){console.log('isHot被修改了',newValue,oldValue)}})</script>
</html>
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>天气案例_深度监视</title><!-- 引入Vue --><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 深度监视:(1).Vue中的watch默认不监测对象内部值的改变(一层)。(2).配置deep:true可以监测对象内部值改变(多层)。备注:(1).Vue自身可以监测对象内部值的改变,但Vue提供的watch默认不可以!(2).使用watch时根据数据的具体结构,决定是否采用深度监视。--><!-- 准备好一个容器--><div id="root"><h2>今天天气很{{info}}</h2><button @click="changeWeather">切换天气</button><hr/><h3>a的值是:{{numbers.a}}</h3><button @click="numbers.a++">点我让a+1</button><h3>b的值是:{{numbers.b}}</h3><button @click="numbers.b++">点我让b+1</button><button @click="numbers = {a:666,b:888}">彻底替换掉numbers</button>{{d.e}}</div></body><script type="text/javascript"&fig.productionTip = false //阻止 vue 在启动时生成生产提示。const vm = new Vue({el:'#root',data:{isHot:true,numbers:{a:1,b:1,c:{d:{e:100}}}},computed:{info(){return this.isHot ? '炎热' : '凉爽'}},methods: {changeWeather(){this.isHot = !this.isHot}},watch:{isHot:{// immediate:true, //初始化时让handler调用一下//handler什么时候调用?当isHot发生改变时。handler(newValue,oldValue){console.log('isHot被修改了',newValue,oldValue)}},//监视多级结构中某个属性的变化/* 'numbers.a':{handler(){console.log('a被改变了')}} *///监视多级结构中所有属性的变化numbers:{deep:true,handler(){console.log('numbers改变了')}}}})</script>
</html>
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>天气案例_监视属性_简写</title><!-- 引入Vue --><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 准备好一个容器--><div id="root"><h2>今天天气很{{info}}</h2><button @click="changeWeather">切换天气</button></div></body><script type="text/javascript"&fig.productionTip = false //阻止 vue 在启动时生成生产提示。const vm = new Vue({el:'#root',data:{isHot:true,},computed:{info(){return this.isHot ? '炎热' : '凉爽'}},methods: {changeWeather(){this.isHot = !this.isHot}},watch:{//正常写法/* isHot:{// immediate:true, //初始化时让handler调用一下// deep:true,//深度监视handler(newValue,oldValue){console.log('isHot被修改了',newValue,oldValue)}}, *///简写/* isHot(newValue,oldValue){console.log('isHot被修改了',newValue,oldValue,this)} */}})//正常写法/* vm.$watch('isHot',{immediate:true, //初始化时让handler调用一下deep:true,//深度监视handler(newValue,oldValue){console.log('isHot被修改了',newValue,oldValue)}}) *///简写/* vm.$watch('isHot',(newValue,oldValue)=>{console.log('isHot被修改了',newValue,oldValue,this)}) */</script>
</html>
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>姓名案例_watch实现</title><!-- 引入Vue --><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 准备好一个容器--><div id="root">姓:<input type="text" v-model="firstName"> <br/><br/>名:<input type="text" v-model="lastName"> <br/><br/>全名:<span>{{fullName}}</span> <br/><br/></div></body><script type="text/javascript"&fig.productionTip = false //阻止 vue 在启动时生成生产提示。const vm = new Vue({el:'#root',data:{firstName:'张',lastName:'三',fullName:'张-三'},watch:{firstName(val){setTimeout(()=>{console.log(this)this.fullName = val + '-' + this.lastName},1000);},lastName(val){this.fullName = this.firstName + '-' + val}}})</script>
</html>
绑定样式:
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>绑定样式</title><style>.basic{width: 400px;height: 100px;border: 1px solid black;}.happy{border: 4px solid red;;background-color: rgba(255, 255, 0, 0.644);background: linear-gradient(30deg,yellow,pink,orange,yellow);}.sad{border: 4px dashed rgb(2, 197, 2);background-color: gray;}.normal{background-color: skyblue;}.atguigu1{background-color: yellowgreen;}.atguigu2{font-size: 30px;text-shadow:2px 2px 10px red;}.atguigu3{border-radius: 20px;}</style><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 准备好一个容器--><div id="root"><!-- 绑定class样式--字符串写法,适用于:样式的类名不确定,需要动态指定 --><div class="basic" :class="mood" @click="changeMood">{{name}}</div> <br/><br/><!-- 绑定class样式--数组写法,适用于:要绑定的样式个数不确定、名字也不确定 --><div class="basic" :class="classArr">{{name}}</div> <br/><br/><!-- 绑定class样式--对象写法,适用于:要绑定的样式个数确定、名字也确定,但要动态决定用不用 --><div class="basic" :class="classObj">{{name}}</div> <br/><br/><!-- 绑定style样式--对象写法 --><div class="basic" :style="styleObj">{{name}}</div> <br/><br/><!-- 绑定style样式--数组写法 --><div class="basic" :style="styleArr">{{name}}</div></div></body><script type="text/javascript"&fig.productionTip = falseconst vm = new Vue({el:'#root',data:{name:'尚硅谷',mood:'normal',classArr:['atguigu1','atguigu2','atguigu3'],classObj:{atguigu1:false,atguigu2:false,},styleObj:{fontSize: '40px',color:'red',},styleObj2:{backgroundColor:'orange'},styleArr:[{fontSize: '40px',color:'blue',},{backgroundColor:'gray'}]},methods: {changeMood(){const arr = ['happy','sad','normal']const index = Math.floor(Math.random()*d = arr[index]}},})</script></html>
写法:
备注:使用v-if的时,元素可能无法获取到,而使用v-show一定可以获取到。
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>条件渲染</title><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 准备好一个容器--><div id="root"><h2>当前的n值是:{{n}}</h2><button @click="n++">点我n+1</button><!-- 使用v-show做条件渲染 --><!-- <h2 v-show="false">欢迎来到{{name}}</h2> --><!-- <h2 v-show="1 === 1">欢迎来到{{name}}</h2> --><!-- 使用v-if做条件渲染 --><!-- <h2 v-if="false">欢迎来到{{name}}</h2> --><!-- <h2 v-if="1 === 1">欢迎来到{{name}}</h2> --><!-- v-else和v-else-if --><!-- <div v-if="n === 1">Angular</div><div v-else-if="n === 2">React</div><div v-else-if="n === 3">Vue</div><div v-else>哈哈</div> --><!-- v-if与template的配合使用 --><template v-if="n === 1"><h2>你好</h2><h2>尚硅谷</h2><h2>北京</h2></template></div></body><script type="text/javascript"&fig.productionTip = falseconst vm = new Vue({el:'#root',data:{name:'尚硅谷',n:0}})</script>
</html>
基本列表:
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>基本列表</title><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 准备好一个容器--><div id="root"><!-- 遍历数组 --><h2>人员列表(遍历数组)</h2><ul><li v-for="(p,index) of persons" :key="index">{{p.name}}-{{p.age}}</li></ul><!-- 遍历对象 --><h2>汽车信息(遍历对象)</h2><ul><li v-for="(value,k) of car" :key="k">{{k}}-{{value}}</li></ul><!-- 遍历字符串 --><h2>测试遍历字符串(用得少)</h2><ul><li v-for="(char,index) of str" :key="index">{{char}}-{{index}}</li></ul><!-- 遍历指定次数 --><h2>测试遍历指定次数(用得少)</h2><ul><li v-for="(number,index) of 5" :key="index">{{index}}-{{number}}</li></ul></div><script type="text/javascript"&fig.productionTip = falsenew Vue({el:'#root',data:{persons:[{id:'001',name:'张三',age:18},{id:'002',name:'李四',age:19},{id:'003',name:'王五',age:20}],car:{name:'奥迪A8',price:'70万',color:'黑色'},str:'hello'}})</script>
</html>
面试题:react、vue中的key有什么作用?(key的内部原理)
旧虚拟DOM中找到了与新虚拟DOM相同的key:
若虚拟DOM中内容没变, 直接使用之前的真实DOM!若虚拟DOM中内容变了, 则生成新的真实DOM,随后替换掉页面中之前的真实DOM。
旧虚拟DOM中未找到与新虚拟DOM相同的key:
创建新的真实DOM,随后渲染到到页面。
若对数据进行:逆序添加、逆序删除等破坏顺序操作:
会产生没有必要的真实DOM更新 ==> 界面效果没问题, 但效率低。如果结构中还包含输入类的DOM:会产生错误DOM更新 ==> 界面有问题。
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>key的原理</title><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 准备好一个容器--><div id="root"><!-- 遍历数组 --><h2>人员列表(遍历数组)</h2><button ="add">添加一个老刘</button><ul><li v-for="(p,index) of persons" :key="index">{{p.name}}-{{p.age}}<input type="text"></li></ul></div><script type="text/javascript"&fig.productionTip = falsenew Vue({el:'#root',data:{persons:[{id:'001',name:'张三',age:18},{id:'002',name:'李四',age:19},{id:'003',name:'王五',age:20}]},methods: {add(){const p = {id:'004',name:'老刘',age:40}this.persons.unshift(p)}},})</script>
</html>
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>列表过滤</title><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 准备好一个容器--><div id="root"><h2>人员列表</h2><input type="text" placeholder="请输入名字" v-model="keyWord"><ul><li v-for="(p,index) of filPerons" :key="index">{{p.name}}-{{p.age}}-{{p.sex}}</li></ul></div><script type="text/javascript"&fig.productionTip = false//用watch实现//#region /* new Vue({el:'#root',data:{keyWord:'',persons:[{id:'001',name:'马冬梅',age:19,sex:'女'},{id:'002',name:'周冬雨',age:20,sex:'女'},{id:'003',name:'周杰伦',age:21,sex:'男'},{id:'004',name:'温兆伦',age:22,sex:'男'}],filPerons:[]},watch:{keyWord:{immediate:true,handler(val){this.filPerons = this.persons.filter((p)=>{return p.name.indexOf(val) !== -1})}}}}) *///#endregion//用computed实现new Vue({el:'#root',data:{keyWord:'',persons:[{id:'001',name:'马冬梅',age:19,sex:'女'},{id:'002',name:'周冬雨',age:20,sex:'女'},{id:'003',name:'周杰伦',age:21,sex:'男'},{id:'004',name:'温兆伦',age:22,sex:'男'}]},computed:{filPerons(){return this.persons.filter((p)=>{return p.name.indexOf(this.keyWord) !== -1})}}}) </script>
</html>
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>列表排序</title><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 准备好一个容器--><div id="root"><h2>人员列表</h2><input type="text" placeholder="请输入名字" v-model="keyWord"><button @click="sortType = 2">年龄升序</button><button @click="sortType = 1">年龄降序</button><button @click="sortType = 0">原顺序</button><ul><li v-for="(p,index) of filPerons" :key="p.id">{{p.name}}-{{p.age}}-{{p.sex}}<input type="text"></li></ul></div><script type="text/javascript"&fig.productionTip = falsenew Vue({el:'#root',data:{keyWord:'',sortType:0, //0原顺序 1降序 2升序persons:[{id:'001',name:'马冬梅',age:30,sex:'女'},{id:'002',name:'周冬雨',age:31,sex:'女'},{id:'003',name:'周杰伦',age:18,sex:'男'},{id:'004',name:'温兆伦',age:19,sex:'男'}]},computed:{filPerons(){const arr = this.persons.filter((p)=>{return p.name.indexOf(this.keyWord) !== -1})//判断一下是否需要排序if(this.sortType){arr.sort((p1,p2)=>{return this.sortType === 1 ? p2.age-p1.age : p1.age-p2.age})}return arr}}}) </script>
</html>
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>更新时的一个问题</title><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 准备好一个容器--><div id="root"><h2>人员列表</h2><button @click="updateMei">更新马冬梅的信息</button><ul><li v-for="(p,index) of persons" :key="p.id">{{p.name}}-{{p.age}}-{{p.sex}}</li></ul></div><script type="text/javascript"&fig.productionTip = falseconst vm = new Vue({el:'#root',data:{persons:[{id:'001',name:'马冬梅',age:30,sex:'女'},{id:'002',name:'周冬雨',age:31,sex:'女'},{id:'003',name:'周杰伦',age:18,sex:'男'},{id:'004',name:'温兆伦',age:19,sex:'男'}]},methods: {updateMei(){// this.persons[0].name = '马老师' //奏效// this.persons[0].age = 50 //奏效// this.persons[0].sex = '男' //奏效// this.persons[0] = {id:'001',name:'马老师',age:50,sex:'男'} //不奏效this.persons.splice(0,1,{id:'001',name:'马老师',age:50,sex:'男'})}}}) </script>
</html>
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>Vue监测数据改变的原理</title><!-- 引入Vue --><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 准备好一个容器--><div id="root"><h2>学校名称:{{name}}</h2><h2>学校地址:{{address}}</h2></div></body><script type="text/javascript"&fig.productionTip = false //阻止 vue 在启动时生成生产提示。const vm = new Vue({el:'#root',data:{name:'尚硅谷',address:'北京',student:{name:'tom',age:{rAge:40,sAge:29,},friends:[{name:'jerry',age:35}]}}})</script>
</html>
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>Document</title></head><body><script type="text/javascript" >let data = {name:'尚硅谷',address:'北京',}//创建一个监视的实例对象,用于监视data中属性的变化const obs = new Observer(data) console.log(obs) //准备一个vm实例对象let vm = {}vm._data = data = obsfunction Observer(obj){//汇总对象中所有的属性形成一个数组const keys = Object.keys(obj)//遍历keys.forEach((k)=>{Object.defineProperty(this,k,{get(){return obj[k]},set(val){console.log(`${k}被改了,我要去解析模板,生成虚拟我要开始忙了`)obj[k] = val}})})}</script></body>
</html>
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>Vue监测数据改变的原理</title><!-- 引入Vue --><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 准备好一个容器--><div id="root"><h1>学校信息</h1><h2>学校名称:{{school.name}}</h2><h2>学校地址:{{school.address}}</h2><h2>校长是:{{school.leader}}</h2><hr/><h1>学生信息</h1><button @click="addSex">添加一个性别属性,默认值是男</button><h2>姓名:{{student.name}}</h2><h2 v-if="student.sex">性别:{{student.sex}}</h2><h2>年龄:真实{{student.age.rAge}},对外{{student.age.sAge}}</h2><h2>朋友们</h2><ul><li v-for="(f,index) in student.friends" :key="index">{{f.name}}--{{f.age}}</li></ul></div></body><script type="text/javascript"&fig.productionTip = false //阻止 vue 在启动时生成生产提示。const vm = new Vue({el:'#root',data:{school:{name:'尚硅谷',address:'北京',},student:{name:'tom',age:{rAge:40,sAge:29,},friends:[{name:'jerry',age:35},{name:'tony',age:36}]}},methods: {addSex(){// Vue.set(this.student,'sex','男')this.$set(this.student,'sex','男')}}})</script>
</html>
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>Vue监测数据改变的原理_数组</title><!-- 引入Vue --><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 准备好一个容器--><div id="root"><h1>学校信息</h1><h2>学校名称:{{school.name}}</h2><h2>学校地址:{{school.address}}</h2><h2>校长是:{{school.leader}}</h2><hr/><h1>学生信息</h1><button @click="addSex">添加一个性别属性,默认值是男</button><h2>姓名:{{student.name}}</h2><h2 v-if="student.sex">性别:{{student.sex}}</h2><h2>年龄:真实{{student.age.rAge}},对外{{student.age.sAge}}</h2><h2>爱好</h2><ul><li v-for="(h,index) in student.hobby" :key="index">{{h}}</li></ul><h2>朋友们</h2><ul><li v-for="(f,index) in student.friends" :key="index">{{f.name}}--{{f.age}}</li></ul></div></body><script type="text/javascript"&fig.productionTip = false //阻止 vue 在启动时生成生产提示。const vm = new Vue({el:'#root',data:{school:{name:'尚硅谷',address:'北京',},student:{name:'tom',age:{rAge:40,sAge:29,},hobby:['抽烟','喝酒','烫头'],friends:[{name:'jerry',age:35},{name:'tony',age:36}]}},methods: {addSex(){// Vue.set(this.student,'sex','男')this.$set(this.student,'sex','男')}}})</script>
</html>
Vue监视数据的原理:
vue会监视data中所有层次的数据。
如何监测对象中的数据?
通过setter实现监视,且要在new Vue时就传入要监测的数据。
对象中后追加的属性,Vue默认不做响应式处理
如需给后添加的属性做响应式,请使用如下API:
Vue.set(target,propertyName/index,value) 或 vm.$set(target,propertyName/index,value)
特别注意:Vue.set() 和 vm.$set() 不能给vm 或 vm的根数据对象 添加属性!!!
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>总结数据监视</title><style>button{margin-top: 10px;}</style><!-- 引入Vue --><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 准备好一个容器--><div id="root"><h1>学生信息</h1><button @click="student.age++">年龄+1岁</button> <br/><button @click="addSex">添加性别属性,默认值:男</button> <br/><button @click="student.sex = '未知' ">修改性别</button> <br/><button @click="addFriend">在列表首位添加一个朋友</button> <br/><button @click="updateFirstFriendName">修改第一个朋友的名字为:张三</button> <br/><button @click="addHobby">添加一个爱好</button> <br/><button @click="updateHobby">修改第一个爱好为:开车</button> <br/><button @click="removeSmoke">过滤掉爱好中的抽烟</button> <br/><h3>姓名:{{student.name}}</h3><h3>年龄:{{student.age}}</h3><h3 v-if="student.sex">性别:{{student.sex}}</h3><h3>爱好:</h3><ul><li v-for="(h,index) in student.hobby" :key="index">{{h}}</li></ul><h3>朋友们:</h3><ul><li v-for="(f,index) in student.friends" :key="index">{{f.name}}--{{f.age}}</li></ul></div></body><script type="text/javascript"&fig.productionTip = false //阻止 vue 在启动时生成生产提示。const vm = new Vue({el:'#root',data:{student:{name:'tom',age:18,hobby:['抽烟','喝酒','烫头'],friends:[{name:'jerry',age:35},{name:'tony',age:36}]}},methods: {addSex(){// Vue.set(this.student,'sex','男')this.$set(this.student,'sex','男')},addFriend(){this.student.friends.unshift({name:'jack',age:70})},updateFirstFriendName(){this.student.friends[0].name = '张三'},addHobby(){this.student.hobby.push('学习')},updateHobby(){// this.student.hobby.splice(0,1,'开车')// Vue.set(this.student.hobby,0,'开车')this.$set(this.student.hobby,0,'开车')},removeSmoke(){this.student.hobby = this.student.hobby.filter((h)=>{return h !== '抽烟'})}}})</script>
</html>
若:<input type="text"/>,则v-model收集的是value值,用户输入的就是value值。若:<input type="radio"/>,则v-model收集的是value值,且要给标签配置value值。若:<input type="checkbox"/>1.没有配置input的value属性,那么收集的就是checked(勾选 or 未勾选,是布尔值)2.配置input的value属性:(1)v-model的初始值是非数组,那么收集的就是checked(勾选 or 未勾选,是布尔值)(2)v-model的初始值是数组,那么收集的的就是value组成的数组
备注:v-model的三个修饰符:
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>收集表单数据</title><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 准备好一个容器--><div id="root"><form @submit.prevent="demo">账号:<input type="text" im="userInfo.account"> <br/><br/>密码:<input type="password" v-model="userInfo.password"> <br/><br/>年龄:<input type="number" v-model.number="userInfo.age"> <br/><br/>性别:男<input type="radio" name="sex" v-model="userInfo.sex" value="male">女<input type="radio" name="sex" v-model="userInfo.sex" value="female"> <br/><br/>爱好:学习<input type="checkbox" v-model="userInfo.hobby" value="study">打游戏<input type="checkbox" v-model="userInfo.hobby" value="game">吃饭<input type="checkbox" v-model="userInfo.hobby" value="eat"><br/><br/>所属校区<select v-model="userInfo.city"><option value="">请选择校区</option><option value="beijing">北京</option><option value="shanghai">上海</option><option value="shenzhen">深圳</option><option value="wuhan">武汉</option></select><br/><br/>其他信息:<textarea v-model.lazy=her"></textarea> <br/><br/><input type="checkbox" v-model="userInfo.agree">阅读并接受<a href="">《用户协议》</a><button>提交</button></form></div></body><script type="text/javascript"&fig.productionTip = falsenew Vue({el:'#root',data:{userInfo:{account:'',password:'',age:18,sex:'female',hobby:[],city:'beijing',other:'',agree:''}},methods: {demo(){console.log(JSON.stringify(this.userInfo))}}})</script>
</html>
定义:
对要显示的数据进行特定格式化后再显示(适用于一些简单逻辑的处理)。
语法:
备注:
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>过滤器</title><script type="text/javascript" src="../js/vue.js"></script><script type="text/javascript" src="../js/dayjs.min.js"></script></head><body><!-- 准备好一个容器--><div id="root"><h2>显示格式化后的时间</h2><!-- 计算属性实现 --><h3>现在是:{{fmtTime}}</h3><!-- methods实现 --><h3>现在是:{{getFmtTime()}}</h3><!-- 过滤器实现 --><h3>现在是:{{time | timeFormater}}</h3><!-- 过滤器实现(传参) --><h3>现在是:{{time | timeFormater('YYYY_MM_DD') | mySlice}}</h3><h3 :x="msg | mySlice">尚硅谷</h3></div><div id="root2"><h2>{{msg | mySlice}}</h2></div></body><script type="text/javascript"&fig.productionTip = false//全局过滤器Vue.filter('mySlice',function(value){return value.slice(0,4)})new Vue({el:'#root',data:{time:1621561377603, //时间戳msg:'你好,尚硅谷'},computed: {fmtTime(){return dayjs(this.time).format('YYYY年MM月DD日 HH:mm:ss')}},methods: {getFmtTime(){return dayjs(this.time).format('YYYY年MM月DD日 HH:mm:ss')}},//局部过滤器filters:{timeFormater(value,str='YYYY年MM月DD日 HH:mm:ss'){// console.log('@',value)return dayjs(value).format(str)}}})new Vue({el:'#root2',data:{msg:'hello,atguigu!'}})</script>
</html>
我们学过的指令:v-bind : 单向绑定解析表达式, 可简写为 :xxxv-model : 双向数据绑定v-for : 遍历数组/对象/字符串v-on : 绑定事件监听, 可简写为@v-if : 条件渲染(动态控制节点是否存存在)v-else : 条件渲染(动态控制节点是否存存在)v-show : 条件渲染 (动态控制节点是否展示)
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>v-text指令</title><!-- 引入Vue --><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 准备好一个容器--><div id="root"><div>你好,{{name}}</div><div v-text="name"></div><div v-text="str"></div></div></body><script type="text/javascript"&fig.productionTip = false //阻止 vue 在启动时生成生产提示。new Vue({el:'#root',data:{name:'尚硅谷',str:'<h3>你好啊!</h3>'}})</script>
</html>
作用:
向指定节点中渲染包含html结构的内容。
与插值语法的区别:
- v-html会替换掉节点中所有的内容,{{xx}}则不会。
- v-html可以识别html结构。
严重注意:
v-html有安全性问题!!!!
(1).在网站上动态渲染任意HTML是非常危险的,容易导致XSS攻击。
(2).一定要在可信的内容上使用v-html,永不要用在用户提交的内容上!
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>v-html指令</title><!-- 引入Vue --><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 准备好一个容器--><div id="root"><div>你好,{{name}}</div><div v-html="str"></div><div v-html="str2"></div></div></body><script type="text/javascript"&fig.productionTip = false //阻止 vue 在启动时生成生产提示。new Vue({el:'#root',data:{name:'尚硅谷',str:'<h3>你好啊!</h3>',str2:'<a href=javascript:location.href="?"kie>兄弟我找到你想要的资源了,快来!</a>',}})</script>
</html>
v-cloak指令(没有值):
- 本质是一个特殊属性,Vue实例创建完毕并接管容器后,会删掉v-cloak属性。
- 使用css配合v-cloak可以解决网速慢时页面展示出{{xxx}}的问题
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>v-cloak指令</title><style>[v-cloak]{display:none;}</style><!-- 引入Vue --></head><body><!-- 准备好一个容器--><div id="root"><h2 v-cloak>{{name}}</h2></div><script type="text/javascript" src="localhost:8080/resource/5s/vue.js"></script></body><script type="text/javascript">console.log(fig.productionTip = false //阻止 vue 在启动时生成生产提示。new Vue({el:'#root',data:{name:'尚硅谷'}})</script>
</html>
- v-once所在节点在初次动态渲染后,就视为静态内容了。
- 以后数据的改变不会引起v-once所在结构的更新,可以用于优化性能。
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>v-once指令</title><!-- 引入Vue --><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 准备好一个容器--><div id="root"><h2 v-once>初始化的n值是:{{n}}</h2><h2>当前的n值是:{{n}}</h2><button @click="n++">点我n+1</button></div></body><script type="text/javascript"&fig.productionTip = false //阻止 vue 在启动时生成生产提示。new Vue({el:'#root',data:{n:1}})</script>
</html>
- 跳过其所在节点的编译过程。
- 可利用它跳过:没有使用指令语法、没有使用插值语法的节点,会加快编译。
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>v-pre指令</title><!-- 引入Vue --><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 准备好一个容器--><div id="root"><h2 v-pre>Vue其实很简单</h2><h2 >当前的n值是:{{n}}</h2><button @click="n++">点我n+1</button></div></body><script type="text/javascript"&fig.productionTip = false //阻止 vue 在启动时生成生产提示。new Vue({el:'#root',data:{n:1}})</script>
</html>
定义语法:
new Vue({
directives:{指令名:配置对象} 或 directives{指令名:回调函数}
})
Vue.directive(指令名,配置对象) 或 Vue.directive(指令名,回调函数)
配置对象中常用的3个回调:
(1).bind:指令与元素成功绑定时调用。
(2).inserted:指令所在元素被插入页面时调用。
(3).update:指令所在模板结构被重新解析时调用。
备注:
1.指令定义时不加v-,但使用时要加v-;
2.指令名如果是多个单词,要使用kebab-case命名方式,不要用camelCase命名。
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>自定义指令</title><script type="text/javascript" src="../js/vue.js"></script></head><body><!--需求1:定义一个v-big指令,和v-text功能类似,但会把绑定的数值放大10倍。需求2:定义一个v-fbind指令,和v-bind功能类似,但可以让其所绑定的input元素默认获取焦点。
-->><!-- 准备好一个容器--><div id="root"><h2>{{name}}</h2><h2>当前的n值是:<span v-text="n"></span> </h2><!-- <h2>放大10倍后的n值是:<span v-big-number="n"></span> </h2> --><h2>放大10倍后的n值是:<span v-big="n"></span> </h2><button @click="n++">点我n+1</button><hr/><input type="text" v-fbind:value="n"></div></body><script type="text/javascript"&fig.productionTip = false//定义全局指令/* Vue.directive('fbind',{//指令与元素成功绑定时(一上来)bind(element,binding){element.value = binding.value},//指令所在元素被插入页面时inserted(element,binding){element.focus()},//指令所在的模板被重新解析时update(element,binding){element.value = binding.value}}) */new Vue({el:'#root',data:{name:'尚硅谷',n:1},directives:{//big函数何时会被调用?1.指令与元素成功绑定时(一上来)。2.指令所在的模板被重新解析时。/* 'big-number'(element,binding){// console.log('big')element.innerText = binding.value * 10}, */big(element,binding){console.log('big',this) //注意此处的this是window// console.log('big')element.innerText = binding.value * 10},fbind:{//指令与元素成功绑定时(一上来)bind(element,binding){element.value = binding.value},//指令所在元素被插入页面时inserted(element,binding){element.focus()},//指令所在的模板被重新解析时update(element,binding){element.value = binding.value}}}})</script>
</html>
生命周期:
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>引出生命周期</title><!-- 引入Vue --><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 准备好一个容器--><div id="root"><h2 v-if="a">你好啊</h2><h2 :style="{opacity}">欢迎学习Vue</h2></div></body><script type="text/javascript"&fig.productionTip = false //阻止 vue 在启动时生成生产提示。new Vue({el:'#root',data:{a:false,opacity:1},methods: {},//Vue完成模板的解析并把初始的真实DOM元素放入页面后(挂载完毕)调用mountedmounted(){console.log('mounted',this)setInterval(() => {this.opacity -= 0.01if(this.opacity <= 0) this.opacity = 1},16)},})//通过外部的定时器实现(不推荐)/* setInterval(() => {vm.opacity -= 0.01if(vm.opacity <= 0) vm.opacity = 1},16) */</script>
</html>
分析生命周期
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>分析生命周期</title><!-- 引入Vue --><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 准备好一个容器--><div id="root" :x="n"><h2 v-text="n"></h2><h2>当前的n值是:{{n}}</h2><button @click="add">点我n+1</button><button @click="bye">点我销毁vm</button></div></body><script type="text/javascript"&fig.productionTip = false //阻止 vue 在启动时生成生产提示。new Vue({el:'#root',// template:`// <div>// <h2>当前的n值是:{{n}}</h2>// <button @click="add">点我n+1</button>// </div>// `,data:{n:1},methods: {add(){console.log('add')this.n++},bye(){console.log('bye')this.$destroy()}},watch:{n(){console.log('n变了')}},beforeCreate() {console.log('beforeCreate')},created() {console.log('created')},beforeMount() {console.log('beforeMount')},mounted() {console.log('mounted')},beforeUpdate() {console.log('beforeUpdate')},updated() {console.log('updated')},beforeDestroy() {console.log('beforeDestroy')},destroyed() {console.log('destroyed')},})</script>
</html>
常用的生命周期钩子:
关于销毁Vue实例
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>引出生命周期</title><!-- 引入Vue --><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 准备好一个容器--><div id="root"><h2 :style="{opacity}">欢迎学习Vue</h2><button @click="opacity = 1">透明度设置为1</button><button @click="stop">点我停止变换</button></div></body><script type="text/javascript"&fig.productionTip = false //阻止 vue 在启动时生成生产提示。new Vue({el:'#root',data:{opacity:1},methods: {stop(){this.$destroy()}},//Vue完成模板的解析并把初始的真实DOM元素放入页面后(挂载完毕)调用mountedmounted(){console.log('mounted',this)this.timer = setInterval(() => {console.log('setInterval')this.opacity -= 0.01if(this.opacity <= 0) this.opacity = 1},16)},beforeDestroy() {clearInterval(this.timer)console.log('vm即将驾鹤西游了')},})</script>
</html>
Vue中使用组件的三大步骤:
- 定义组件(创建组件)
- 注册组件
- 使用组件(写组件标签)
如何定义一个组件?
使用d(options)创建,其中options和new Vue(options)时传入的那个options几乎一样,但也有点区别;区别如下:
- el不要写,为什么? ——— 最终所有的组件都要经过一个vm的管理,由vm中的el决定服务哪个容器。
- data必须写成函数,为什么? ———— 避免组件被复用时,数据存在引用关系。
备注:使用template可以配置组件结构。
如何注册组件?
- 局部注册:靠new Vue的时候传入components选项
- 全局注册:靠Vueponent(‘组件名’,组件)
编写组件标签:
<school></school>
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>基本使用</title><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 准备好一个容器--><div id="root"><hello></hello><hr><h1>{{msg}}</h1><hr><!-- 第三步:编写组件标签 --><school></school><hr><!-- 第三步:编写组件标签 --><student></student></div><div id="root2"><hello></hello></div></body><script type="text/javascript"&fig.productionTip = false//第一步:创建school组件const school = d({template:`<div class="demo"><h2>学校名称:{{schoolName}}</h2><h2>学校地址:{{address}}</h2><button @click="showName">点我提示学校名</button> </div>`,// el:'#root', //组件定义时,一定不要写el配置项,因为最终所有的组件都要被一个vm管理,由vm决定服务于哪个容器。data(){return {schoolName:'尚硅谷',address:'北京昌平'}},methods: {showName(){alert(this.schoolName)}},})//第一步:创建student组件const student = d({template:`<div><h2>学生姓名:{{studentName}}</h2><h2>学生年龄:{{age}}</h2></div>`,data(){return {studentName:'张三',age:18}}})//第一步:创建hello组件const hello = d({template:`<div> <h2>你好啊!{{name}}</h2></div>`,data(){return {name:'Tom'}}})//第二步:全局注册组件Vueponent('hello',hello)//创建vmnew Vue({el:'#root',data:{msg:'你好啊!'},//第二步:注册组件(局部注册)components:{school,student}})new Vue({el:'#root2',})</script>
</html>
第一种写法:<school></school>第二种写法:<school/>备注:不用使用脚手架时,<school/>会导致后续组件不能渲染。
const school = d(options)
可简写为:
const school = options
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>几个注意点</title><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 准备好一个容器--><div id="root"><h1>{{msg}}</h1><school></school></div></body><script type="text/javascript"&fig.productionTip = false//定义组件const s = d({name:'atguigu',template:`<div><h2>学校名称:{{name}}</h2> <h2>学校地址:{{address}}</h2> </div>`,data(){return {name:'尚硅谷',address:'北京'}}})new Vue({el:'#root',data:{msg:'欢迎学习Vue!'},components:{school:s}})</script>
</html>
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>组件的嵌套</title><!-- 引入Vue --><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 准备好一个容器--><div id="root"></div></body><script type="text/javascript"&fig.productionTip = false //阻止 vue 在启动时生成生产提示。//定义student组件const student = d({name:'student',template:`<div><h2>学生姓名:{{name}}</h2> <h2>学生年龄:{{age}}</h2> </div>`,data(){return {name:'尚硅谷',age:18}}})//定义school组件const school = d({name:'school',template:`<div><h2>学校名称:{{name}}</h2> <h2>学校地址:{{address}}</h2> <student></student></div>`,data(){return {name:'尚硅谷',address:'北京'}},//注册组件(局部)components:{student}})//定义hello组件const hello = d({template:`<h1>{{msg}}</h1>`,data(){return {msg:'欢迎来到尚硅谷学习!'}}})//定义app组件const app = d({template:`<div> <hello></hello><school></school></div>`,components:{school,hello}})//创建vmnew Vue({template:'<app></app>',el:'#root',//注册组件(局部)components:{app}})</script>
</html>
关于VueComponent:
school组件本质是一个名为VueComponent的构造函数,且不是程序员定义的,是d生成的。
我们只需要写或,Vue解析时会帮我们创建school组件的实例对象,
即Vue帮我们执行的:new VueComponent(options)。
特别注意:每次调用d,返回的都是一个全新的VueComponent!!!!
关于this指向:
(1).组件配置中:
data函数、methods中的函数、watch中的函数、computed中的函数 它们的this均是【VueComponent实例对象】。
(2).new Vue(options)配置中:
data函数、methods中的函数、watch中的函数、computed中的函数 它们的this均是【Vue实例对象】。
VueComponent的实例对象,以后简称vc(也可称之为:组件实例对象)。
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>VueComponent</title><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 准备好一个容器--><div id="root"><school></school><hello></hello></div></body><script type="text/javascript"&fig.productionTip = false//定义school组件const school = d({name:'school',template:`<div><h2>学校名称:{{name}}</h2> <h2>学校地址:{{address}}</h2> <button @click="showName">点我提示学校名</button></div>`,data(){return {name:'尚硅谷',address:'北京'}},methods: {showName(){console.log('showName',this)}},})const test = d({template:`<span>atguigu</span>`})//定义hello组件const hello = d({template:`<div><h2>{{msg}}</h2><test></test> </div>`,data(){return {msg:'你好啊!'}},components:{test}})// console.log('@',school)// console.log('#',hello)//创建vmconst vm = new Vue({el:'#root',components:{school,hello}})</script>
</html>
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>一个重要的内置关系</title><!-- 引入Vue --><script type="text/javascript" src="../js/vue.js"></script></head><body><!-- 准备好一个容器--><div id="root"><school></school></div></body><script type="text/javascript"&fig.productionTip = false //阻止 vue 在启动时生成生产提示。Vue.prototype.x = 99//定义school组件const school = d({name:'school',template:`<div><h2>学校名称:{{name}}</h2> <h2>学校地址:{{address}}</h2> <button @click="showX">点我输出x</button></div>`,data(){return {name:'尚硅谷',address:'北京'}},methods: {showX(){console.log(this.x)}},})//创建一个vmconst vm = new Vue({el:'#root',data:{msg:'你好'},components:{school}})//定义一个构造函数/* function Demo(){this.a = 1this.b = 2}//创建一个Demo的实例对象const d = new Demo()console.log(Demo.prototype) //显示原型属性console.log(d.__proto__) //隐式原型属性console.log(Demo.prototype === d.__proto__)//程序员通过显示原型属性操作原型对象,追加一个x属性,值为99Demo.prototype.x = 99console.log('@',d) */</script>
</html>
App.vue
<template><div><School></School><Student></Student></div>
</template><script>//引入组件import School from './School.vue'import Student from './Student.vue'export default {name:'App',components:{School,Student}}
</script>
index.html
<!DOCTYPE html>
<html><head><meta charset="UTF-8" /><title>练习一下单文件组件的语法</title></head><body><!-- 准备一个容器 --><div id="root"></div><!-- <script type="text/javascript" src="../js/vue.js"></script> --><!-- <script type="text/javascript" src="./main.js"></script> --></body>
</html>
main.js
import App from './App.vue'new Vue({el:'#root',template:`<App></App>`,components:{App},
})
School.vue
<template><div class="demo"><h2>学校名称:{{name}}</h2><h2>学校地址:{{address}}</h2><button @click="showName">点我提示学校名</button> </div>
</template><script>export default {name:'School',data(){return {name:'尚硅谷',address:'北京昌平'}},methods: {showName(){alert(this.name)}},}
</script><style>.demo{background-color: orange;}
</style>
Student.vue
<template><div><h2>学生姓名:{{name}}</h2><h2>学生年龄:{{age}}</h2></div>
</template><script>export default {name:'Student',data(){return {name:'张三',age:18}}}
</script>
本文发布于:2024-02-02 11:38:28,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170684510643547.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |