??最近跟著vue相關視頻學了些vue的基礎知識,做此總結,以防遺忘,
一. Hello Vue
1、引入vue.js:
<script type="text/javascript" src="../js/vue.js"></script>
2、創建Vue物件:
el : 指定根element(選擇器,指定用vue來管理頁面中的哪個標簽區域)
data : 初始化資料
這是html代碼:
<div id="app">
<p>{{message}}</p>
</div>
這是js代碼:
<script type="text/javascript">
//創建vue實體
const vm = new Vue({//配置物件
// 配置選項
el:'#app',//element:選擇器 指定用vue來管理頁面中的哪個標簽區域
data:{//資料(model)
message:'Hello Vue'
}
})
</script>

二. 理解什么是MVM
MVVM指的是
??model:模型,資料物件(data)
??view:視圖,模板頁面
??viewModel:視圖模型(Vue的實體vm)
??其中,model指:data部分

??view指下面這部分:

??viewModel指下面這部分:


三. 雙向資料系結 v-model
<div id="app">
<input type="text" v-model="username" />
<p>Hello {{username}}</p>
</div>
const vm = new Vue({
el:'#app',
data:{
username:'Tom'
}
})


四. 字母轉為大寫 toUpperCase()
<div id="app">
<p>{{msg}}</p> <!--textContent-->
<p>{{msg.toUpperCase()}}</p><!--轉為大寫-->
</div>
<script type="text/javascript">
new Vue({
el:"#app",
data:{
msg:"I Will Back!",
}
})
</script>

五. 文本渲染三種方法 :{{}} 、v-text 和 v-html
{{}}:即textContent,將元素當成純文本輸出,
v-text:即textContent,將元素當成純文本輸出,
v-html:即innerHTML,將元素當成HTML標簽決議后輸出,
<div id="app">
<p>{{msg}}</p> <!--textContent-->
<p v-text="msg"></p> <!--textContent-->
<p v-html="msg"></p> <!--innerHTML-->
</div>
<script type="text/javascript">
new Vue({
el:"#app",
data:{
msg:"<a href='http:/www.atguigu.com'>I Will Back!</a>"
}
})
</script>

六. 強制資料系結 v-bind: ? 簡寫 :
<div id="app">
<img v-bind:src="imgUrl" />
<img :src="imgUrl" />
</div>
<script type="text/javascript">
new Vue({
el:"#app",
data:{
imgUrl:'https://cn.vuejs.org/images/logo.png'
}
})
</script>

七. 系結事件監聽 v-on: ?簡寫 @
<div id="app">
<button v-on:click="test">test1</button>
<button @click="test2('aaa')">test2</button>
</div>
<script type="text/javascript">
new Vue({
el:"#app",
methods:{
test(){
alert('哈哈!');
},
test2(content){
alert(content);
}
}
})
</script>


八. 計算屬性 computed
<div id="demo">
姓: <input type="text" placeholder="First Name" v-model="firstName"><br>
名: <input type="text" placeholder="Last Name" v-model="lastName"><br>
<!--fullName1是根據fistName和lastName計算產生-->
姓名1(單向): <input type="text" placeholder="Full Name1" v-model="fullName1"><br>
</div>
<script type="text/javascript">
const vm = new Vue({
el:"#demo",
data:{
firstName:"A",
lastName:"B"
},
computed:{
//什么時候執行:初始化顯示/相關的data屬性資料發生改變
fullName1(){ //計算屬性中的一個方法,方法的回傳值作為屬性值
return this.firstName+' '+this.lastName
}
}
})
</script>

九.監視 watch?$watch
watch 和 $watch 都能實作監視,
如果想要實作上述 計算屬性實體的效果,需要寫兩個 監視,如下實體:用了一個 watch ,一個 $watch,
<div id="demo">
姓: <input type="text" placeholder="First Name" v-model="firstName"><br>
名: <input type="text" placeholder="Last Name" v-model="lastName"><br>
姓名2(單向): <input type="text" placeholder="Full Name2" v-model="fullName2"><br>
</div>
<script type="text/javascript">
const vm = new Vue({
el:"#demo",
data:{
firstName:"A",
lastName:"B",
fullName2: 'A B'
},
watch:{//配置監視
firstName:function(value){//firstName發生了變化
console.log(this)//就是vm物件
this.fullName2 = value+' '+this.lastName
}
}
})
vm.$watch('lastName',function(value){
//更新fullName2
this.fullName2 = this.firstName+' '+value
})
</script>

十一. 計算屬性之 get 與 set
計算屬性高級:
??通過getter/setter實作對屬性資料的顯示和監視,
??計算屬性存在快取, 多次讀取只執行一次getter計算,
<div id="demo">
姓: <input type="text" placeholder="First Name" v-model="firstName"><br>
名: <input type="text" placeholder="Last Name" v-model="lastName"><br>
姓名3(雙向): <input type="text" placeholder="Full Name3" v-model="fullName3"><br>
</div>
<script type="text/javascript">
const vm = new Vue({
el:"#demo",
data:{
firstName:"A",
lastName:"B"
},
computed:{
fullName3:{
//回呼函式 計算并回傳當前屬性的值
//當獲取當前屬性值時自動呼叫, 將回傳值(根據相關的其它屬性資料)作為屬性值
get(){
return this.firstName+' '+this.lastName
},
// 當屬性值發生了改變時自動呼叫, 監視當前屬性值變化, 同步更新相關的其它屬性值
set(value){
const names = value.split(' ')
this.firstName = names[0]
this.lastName = names[1]
}
}
}
})
</script>

十二. class系結: :class=‘xxx’
三種情況:
??xxx是字串
??xxx是物件
??xxx是陣列
<div id="demo">
<h2>class系結: :class='xxx'</h2>
<p class="classC" :class="a">xxx是字串</p>
<p :class="{classA:isA,classB:isB}">xxx是物件</p>
<p :class="['classA','classC']">xxx是陣列</p>
<button @click="update">更新</button>
</div>
.classA {
color: red;
}
.classB {
background: blue;
}
.classC {
font-size: 20px;
}
<script type="text/javascript">
new Vue({
el:'#demo',
data:{
a:'classA',
isA:true,
isB:false,
},
methods:{
update(){
this.a='classB',
this.isA=false,
this.isB=true
}
}
})
</script>

??點擊更新按鈕后,效果如下:

十三. style系結
<div id="demo">
<p :style="{color: activeColor, fontSize: fontSize + 'px' }">style系結</p>
<button @click="update">更新</button>
</div>
<script type="text/javascript">
new Vue({
el:'#demo',
data:{
activeColor:'red',
fontSize:20
},
methods:{
update(){
this.activeColor='green',
this.fontSize=30
}
}
})
</script>

??點擊更新按鈕后,效果如下:

十四. 條件渲染
??1. 條件渲染指令
?? ??v-if:能確保在切換程序中條件塊內的事件監聽器和子組件適當地被銷毀和重建,但如果在初始渲染時條件為假,則什么也不做,直到條件第一次變為真時,才會開始渲染,
?? ??v-else
?? ?? v-show:不管初始條件是什么,元素總是會被渲染,并且只是簡單地基于 CSS 進行切換,
??2. 比較v-if與v-show
?? ??如果需要頻繁切換, v-show 較好
?? ??如果在運行時條件很少改變,則使用 v-if 較好,
<div id="demo">
<p v-if="ok">成功了</p>
<p v-else>失敗了</p>
<p v-show="ok">表白成功</p>
<p v-show="!ok">表白失敗</p>
<button @click="ok=!ok">切換</button>
</div>
<script type="text/javascript">
new Vue({
el:'#demo',
data:{
ok:true
}
})
</script>

十五. 遍歷 v-for
vue重寫了陣列中的一系列改變陣列內部資料的方法(先呼叫原生,再更新頁面)————>陣列內部改變,頁面自動變化

<div id="demo">
<h2>v-for 遍歷陣列</h2>
<ul>
<li v-for="(p,index) in persons" :key="index">
{{index}}--{{p.name}}--{{p.age}}
---<button @click="deleteP(index)">洗掉</button>
---<button @click="updateP(index, {name:'Cat', age: 16})">更新</button>
</li>
</ul>
<h2>v-for 遍歷物件</h2>
<ul>
<li v-for="(value,key) in persons[1]" :key="key">
{{value}}---{{key}}
</li>
</ul>
</div>
<script type="text/javascript">
//vue本身只是監視了persons的改變,沒有監視陣列內部資料的改變
//vue重寫了陣列中的一系列改變陣列內部資料的方法(先呼叫原生,再更新頁面)————>陣列內部改變,頁面自動變化
new Vue({
el:'#demo',
data:{
persons:[
{name:'Tom',age:18},
{name:'Jack',age:16},
{name:'Bob',age:19},
{name:'Rose',age:17}
]
},
methods:{
deleteP(index){
this.persons.splice(index, 1)
// 呼叫了不是原生陣列的splice(), 而是一個變異(重寫)方法
// 1. 呼叫原生的陣列的對應方法
// 2. 更新界面
},
updateP (index, newP) {
console.log('updateP', index, newP)
this.persons.splice(index, 1, newP)
},
addP (newP) {
this.persons.push(newP)
}
}
})
</script>

十六. 串列搜索和排序
看下面的示例,搜索是通過computed屬性計算出新的陣列,該陣列通過filter對persons陣列進行過濾得到,
排序是通過點擊不同的按鈕傳遞不同的orderType值進行判斷,使用sort方法,
<div id="demo">
<input type="text" v-model="searchName">
<ul>
<li v-for="(p, index) in filterPersons" :key="index">
{{index}}--{{p.name}}--{{p.age}}
</li>
</ul>
<div>
<button @click="setOrderType(1)">年齡升序</button>
<button @click="setOrderType(2)">年齡降序</button>
<button @click="setOrderType(0)">原本順序</button>
</div>
</div>
<script type="text/javascript">
const vm = new Vue({
el: '#demo',
data: {
searchName: '',
orderType: 0, // 0代表原本順序, 1代表升序, 2代表降序
persons: [
{name: 'Tom', age:18},
{name: 'Jack', age:17},
{name: 'Bob', age:19},
{name: 'Mary', age:16}
]
},
computed: {
filterPersons () {
// 取出相關資料
const {searchName, persons, orderType} = this;
//最終需要顯示的陣列
let fPersons;
// 對persons進行過濾
fPersons = persons.filter(p => p.name.indexOf(searchName)!== -1)
// 排序
if(orderType !== 0) {
fPersons.sort(function (p1, p2) {
if(orderType===2) {
// 降序
return p2.age-p1.age
} else {
// 升序
return p1.age-p2.age
}
})
}
return fPersons
}
},
methods: {
setOrderType (orderType) {
this.orderType = orderType
}
}
})
</script>


十七. 事件處理
1. 系結監聽:
(1)v-on:xxx=“fun”
(2)@xxx=“fun”
(3)@xxx=“fun(引數)”
??默認事件形參: event
?? 隱含屬性物件: $event
<div id="example">
<button @click="test1">test1</button>
<button @click="test2('atguigu')">test2</button>
<button @click="test3">test3</button>
<button @click="test4('abcd', $event)">test4</button>
</div>
<script type="text/javascript">
new Vue({
el:'#example',
data:{
},
methods:{
test1 () {
alert('點擊了')
},
test2 (msg) {
alert(msg)
},
test3(event) {
alert(event.target.innerHTML)
},
test4 (msg, event) {
alert(msg+'---'+event.target.textContent)
}
}
})
</script>




2. 事件修飾符:
.prevent : 阻止事件的默認行為 event.preventDefault()
.stop : 停止事件冒泡 event.stopPropagation()
<div id="example">
<div style="width: 200px;height: 200px;background: red" @click="test5">
<div style="width: 100px;height: 100px;background: blue" @click.stop="test6"></div><!--停止冒泡-->
</div>
<a href="http://www.baidu.com" @click.prevent="test7">百度一下</a><!--阻止默認行為-->
</div>
<script type="text/javascript">
new Vue({
el:'#example',
data:{
},
methods:{
test5 () {
alert('out')
},
test6 () {
alert('inner')
},
test7(){
alert('點擊了');
}
}
})
</script>
??可以自己試試,可以發現,事件的默認行為和冒泡行為全部被阻止了,
3. 按鍵修飾符:
.keycode : 操作的是某個keycode值的健
.enter : 操作的是enter鍵,enter鍵的keycode值為13,以下以enter為示例,
<div id="example">
<input type="text" @keyup.13="test8"><!--按enter鍵-->
<input type="text" @keyup.enter="test8"><!--按enter鍵-->
</div>
<script type="text/javascript">
new Vue({
el:'#example',
data:{
},
methods:{
test8(event){
alert(event.target.value+" "+event.keyCode)
}
}
})
</script>


十八. 表單輸入系結
使用v-model(雙向資料系結)自動收集資料
text/textarea
checkbox
radio
select
<div id="demo">
<form action="/xxx" @submit.prevent="handleSubmit">
<span>用戶名: </span>
<input type="text" v-model="username"><br>
<span>密碼: </span>
<input type="password" v-model="pwd"><br>
<span>性別: </span>
<input type="radio" id="female" value="女" v-model="sex">
<label for="female">女</label>
<input type="radio" id="male" value="男" v-model="sex">
<label for="male">男</label>
<br>
<span>愛好: </span>
<input type="checkbox" id="basket" value="basket" v-model="likes">
<label for="basket">籃球</label>
<input type="checkbox" id="foot" value="foot" v-model="likes">
<label for="foot">足球</label>
<input type="checkbox" id="pingpang" value="pingpang" v-model="likes">
<label for="pingpang">乒乓</label>
<br>
<span>城市: </span>
<select v-model="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="info"></textarea><br><br>
<input type="submit" value="注冊">
</form>
</div>
<script type="text/javascript">
new Vue({
el:'#demo',
data: {
username: '',
pwd: '',
sex: '男',
likes: ['foot'],
allCitys: [{id: 1, name: 'BJ'}, {id: 2, name: 'SS'}, {id: 3, name: 'SZ'}],
cityId: '2',
info: ''
},
methods: {
handleSubmit () {
console.log(this.username, this.pwd, this.sex, this.likes, this.cityId, this.info)
alert('提交注冊的ajax請求')
}
}
})
</script>

十九. 生命周期
1. vue物件的生命周期
1). 初始化顯示
* beforeCreate()
* created()
* beforeMount()
* mounted()
2). 更新狀態
* beforeUpdate()
* updated()
3). 銷毀vue實體: vm.$destory()
* beforeDestory()
* destoryed()
2. 常用的生命周期方法
created()/mounted(): 發送ajax請求, 啟動定時器等異步任務
beforeDestory(): 做收尾作業, 如: 清除定時器
<div id="test">
<button @click="destroyVue">destory vue</button>
<p v-if="isShow">尚硅谷IT教育</p>
</div>
<script type="text/javascript">
new Vue({
el: '#test',
data: {
isShow: true
},
beforeCreate() {
console.log('beforeCreate()')
},
created() {
console.log('created()')
},
beforeMount() {
console.log('beforeMount()')
},
mounted() {
// 初始化顯示后立即呼叫
console.log('mounted()')
this.intervalId = setInterval(() => {
console.log('-----')
this.isShow = !this.isShow
}, 1000)
},
beforeUpdate() {
console.log('beforeUpdate()')
},
updated() {
console.log('updated()')
},
beforeDestroy() {
console.log('beforeDestroy()')
// 執行收尾的作業
clearInterval(this.intervalId)
},
destroyed() {
console.log('destroyed()')
},
methods: {
destroyVue() {
this.$destroy()
}
}
})
</script>

附上vue的生命周期圖:

二十. 過渡和影片
1. vue影片的理解
??操作css的trasition或animation
??vue會給目標元素添加/移除特定的class
2. 基本過渡影片的編碼
??1). 在目標元素外包裹
??2). 定義class樣式
?? 1>. 指定過渡樣式: transition
?? 2>. 指定隱藏時的樣式: opacity/其它
3. 過渡的類名
??xxx-enter-active: 指定顯示的transition
??xxx-leave-active: 指定隱藏的transition
??xxx-enter
實體一:
<div id="demo">
<button @click="show = !show">Toggle</button>
<transition name="xxx">
<p v-show="show">hello</p>
</transition>
</div>
/*指定過渡樣式*/
.xxx-enter-active, .xxx-leave-active {
transition: opacity 1s
}
/*指定隱藏時的樣式*/
.xxx-enter, .xxx-leave-to {
opacity: 0;
}
<script type="text/javascript">
new Vue({
el: '#demo',
data: {
show: true
}
})
</script>
實體二:
<div id="demo2">
<button @click="show = !show">Toggle2</button>
<transition name="move">
<p v-show="show">hello</p>
</transition>
</div>
.move-enter-active {
transition: all 1s
}
.move-leave-active {
transition: all 3s
}
.move-enter, .move-leave-to {
opacity: 0;
transform: translateX(20px)
}
<script type="text/javascript">
new Vue({
el: '#demo2',
data: {
show: true
}
})
</script>
實體三:
<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>
在這里插入代碼片
`.bounce-enter-active {
animation: bounce-in .5s;
}
.bounce-leave-active {
animation: bounce-in .5s reverse;
}
@keyframes bounce-in {
0% {
transform: scale(0);
}
50% {
transform: scale(1.5);
}
100% {
transform: scale(1);
}
}
```javascript
<script>
new Vue({
el: '#example-2',
data: {
show: true
}
})
</script>
可自己運行查看效果,
二十一. 過濾器
1. 理解過濾器
功能: 對要顯示的資料進行特定格式化后再顯示
注意: 并沒有改變原本的資料, 而是產生新的對應的資料
2. 編碼
1). 定義過濾器
Vue.filter(filterName, function(value[,arg1,arg2,…]){
// 進行一定的資料處理
return newValue
})
2). 使用過濾器
{{myData | filterName}}
{{myData | filterName(arg)}}
<div id="test">
<h2>顯示格式化的日期時間</h2>
<p>{{time}}</p>
<p>最完整的: {{time | dateString}}</p>
<p>年月日: {{time | dateString('YYYY-MM-DD')}}</p>
<p>時分秒: {{time | dateString('HH:mm:ss')}}</p>
</div>
<script type="text/javascript" src="https://cdn.bootcss.com/moment.js/2.22.1/moment.js"></script>
<script type="text/javascript">
// 定義過濾器
Vue.filter('dateString', function (value, format='YYYY-MM-DD HH:mm:ss') {
return moment(value).format(format);
})
new Vue({
el: '#test',
data: {
time: new Date()
},
mounted () {
setInterval(() => {
this.time = new Date()
}, 1000)
}
})
</script>
這里引入了moment,詳情可查看其官網moment.js
也可以查看我的博客 初識react(13)—— 使用 moment 來獲取日期 ,不過我這篇博客是基于 react 寫的,可以參考著看,下面是上述代碼運行結果:

二十二. 指令
1. 常用內置指令
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物件通過$refs屬性訪問這個元素物件
v-cloak : 使用它防止閃現運算式, 與css配合: [v-cloak] { display: none }
<div id="example">
<p ref="msg">abcd</p>
<button @click="hint">提示</button>
<p v-cloak>{{content}}</p>
</div>
[v-cloak] { display: none }
<script type="text/javascript">
new Vue({
el: '#example',
data: {
content: '<a href="http://www.baidu.com">百度一下</a>'
},
methods: {
hint () {
alert(this.$refs.msg.innerHTML)
}
}
})
</script>

2. 自定義指令
1. 注冊全域指令
Vue.directive(‘my-directive’, function(el, binding){
el.innerHTML = binding.value.toupperCase()
})
2. 注冊區域指令
directives : {
‘my-directive’ : {
bind (el, binding) {
el.innerHTML = binding.value.toupperCase()
}
}
}
3. 使用指令
v-my-directive='xxx’
<div id="test1">
<p v-upper-text="msg"></p>
<p v-lower-text="msg"></p>
</div>
<div id="test2">
<p v-upper-text="msg"></p>
<p v-lower-text="msg"></p>
</div>
<script type="text/javascript">
// 注冊一個全域指令
// el: 指令所在的標簽物件
// binding: 包含指令相關資訊資料的物件
Vue.directive('upper-text', function (el, binding) {
console.log(el, binding)
el.textContent = binding.value.toUpperCase()
})
new Vue({
el: '#test1',
data: {
msg: "I Like You"
},
// 注冊區域指令
directives: {
'lower-text'(el, binding) {
console.log(el, binding)
el.textContent = binding.value.toLowerCase()
}
}
})
new Vue({
el: '#test2',
data: {
msg: "I Like You Too"
}
})
</script>

二十三. 插件
1.首先創建一個js檔案,如:

2.在該js檔案中,寫如下所示代碼,向外暴露該 js 檔案:
(function (window) {
//這里寫入你的代碼
//向外暴露
window.MyPlugin = MyPlugin
})(window)
3.在 html 檔案中引入該 js 檔案:
<script type="text/javascript" src="vue-myPlugin.js"></script>
4.使用 該 js 檔案方法:
Vue.use(MyPlugin)
Vue.xxx()
以上是我通過看視頻學習,對 vue 基礎知識的一次總結,主要是為了方便自己以后翻閱,希望也能幫助到大家,
以上內容來自尚硅谷的視頻,不理解的可以看視頻學習,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/197229.html
標籤:其他
上一篇:事件流
