文章目錄
1.vue語法
這裏使用一個增刪改查的案例來講vue常用的語法羅列
常用語法:
其他語法學習參考網站
2.vue案例
實現一個簡單基於內存的CUD,讀取從web服務器讀取。
2.1 查詢數據
這裏直接使用axios來操作遠程接口 導出數據格式爲:
curl http://192.168.1.35/xxx/tpauth/supportType
{
"success":true,
"code":"200",
"message":"成功",
"time":1572580292756,
"data":[
{"id":1,"name":"微信","iconUrl":"https://www.easyicon.net/download/ico/1230528/32/","loginUrl":"/tpauth/login?code=WEIXIN","authUrl":"/auth/thirdLogin","enable":1,"code":"WEIXIN"},
{"id":2,"name":"支付寶","iconUrl":"https://www.easyicon.net/download/ico/1226611/32/","loginUrl":"/tpauth/login?code=ALIPAY","authUrl":"/auth/thirdLogin","enable":1,"code":"ALIPAY"}
]
}
完整代碼
<template>
<div>
<!--時間 v-on:click 縮寫爲 @click -->
名稱:<input type="button" @click="query" value="查詢"><input type="button" @click="isActive=false;ctype='insert';clear()" value="新增">
<table>
<!--
:style={"css樣式名稱":樣式值是獲取vue變量}
-->
<tr :style="{fontSize:fontSizeVar}">
<td>名稱</td>
<td>圖標</td>
<td>操作</td>
</tr>
<!--任意元素定義了ref屬性 可以在vue中使用this.$refs.ref定義名稱獲取 返回的是一個原始dom元素數組-->
<!--所有v-bind:src="vue屬性值" 都可以簡寫爲:src-->
<tr v-for="(r,index) in thirdList" :ref="'tr_'+index" :class="{o:index%2==0}" @mouseover="mouseover(index)" @mouseout="mouseout(index)">
<td>{{r.name}}</td>
<td><img :src="r.iconUrl"/></td>
<td><button @click="deleteUser(r)">刪除</button><button @click="isActive=false;ctype='update';insertUser.id=r.id;insertUser.name=r.name;insertUser.iconUrl=r.iconUrl">修改</button></td>
</tr>
</table>
<!--
:class="{樣式表名稱:條件}"
就是當vue數據isActive==true是 html中生成樣式表class=active,注意必須在style中定義.active
參考:https://cn.vuejs.org/v2/guide/class-and-style.html
-->
<div :class="{active:isActive}" v-if="!isActive" style="border:1px solid black;width:200px;padding-left: 20px">
用戶名稱:<input v-model="insertUser.name"><br/>
用戶圖標:<input v-model="insertUser.iconUrl"><br/>
<img :src="insertUser.iconUrl"/>
<input type="button" @click="insert" value="保存">
</div>
</div>
</template>
<script>
import axios from "axios"
import UUID from "es6-uuid"
import Vue from 'vue'
const AxiosPlugin={
install(Vue){
//axios攔截器用於在所有請求或者響應時做一些特殊處理
axios.interceptors.request.use(config=>{
//添加請求頭
config.headers.common["SourceFront"]="Test";
return config;
},error=>{
return Promise.reject(error)
})
}
}
export default {
data() {
return {
thirdList: null,
isActive: true,
fontSizeVar:"20px",
currentHoverIndex:0,
ctype:"insert",
insertUser: {
id:"",
name: "",
iconUrl: ""
}
}
},
mounted(){
console.log(axios.interceptors)
//直接調用AxiosPlugin插件install方法,該AxiosPlugin對象無論use多少次都只實例化一個對象 是單例的
//直接使用use來用的話 決定該插件是否使用。
//參考:https://www.jianshu.com/p/89a05706917a
Vue.use(AxiosPlugin)
//調用查詢
this.query()
},
methods: {
mouseover(index){
var srcElement=this.$refs["tr_"+index][0];
srcElement.style.backgroundColor="red";
},
mouseout(index){
var srcElement=this.$refs["tr_"+index][0];
srcElement.style.backgroundColor="";
},
deleteUser(record){
this.thirdList.splice(this.thirdList.findIndex(item=>{
return item==record;
}),1)
},
clear(){
for (var p in this.insertUser){
this.insertUser[p]=""
}
},
insert() {
if(this.ctype==="insert") {
this.insertUser.id=UUID(32)
this.thirdList.push(this.insertUser)
}else{
var index=this.thirdList.findIndex(item=>{
return item.id===this.insertUser.id
})
var item=JSON.parse(JSON.stringify(this.insertUser))
this.thirdList.splice(index,1,item);
}
this.isActive = true
},
query(event) {
var dthis = this;
//鏈式調用承諾將來執行的then和catch是一個異步操作 叫做Promise
//axios.get("http://192.168.1.35/ums/tpauth/supportType1")返回就是一個Promise對象
axios.get("http://192.168.1.35/ums/tpauth/supportType").then(response => {
this.thirdList = response.data.data
}).catch(error=>{
Promise.reject(error);
})
}
}
}
</script>
<style>
table {
border: 0;
margin: 0;
border-collapse: collapse;
border-spacing: 0;
width: 30%;
margin-top: 10px
}
mouseHover {
background-color: red;
}
td {
border: 1px solid black;
}
.active {
display: none;
}
.o {
background-color: gray;
}
</style>
2.2語法解釋
2.2.1 循環
代碼:
<tr v-for="(r,index) in thirdList" :ref="'tr_'+index" :class="{o:index%2==0}" @mouseover="mouseover(index)" @mouseout="mouseout(index)">
<td>{{r.name}}</td>
<td><img :src="r.iconUrl"/></td>
<td><button @click="deleteUser(r)">刪除</button><button @click="isActive=false;ctype='update';insertUser.id=r.id;insertUser.name=r.name;insertUser.iconUrl=r.iconUrl">修改</button></td>
</tr>
v-for="(r,index) in thirdList"表示循環thirdList數據
r表示當前循環行數據index表示當前行索引,其他vue語法中都可以直接使用r和index這兩個變量
2.2.2 if條件
<div :class="{active:isActive}" v-if="!isActive" style="border:1px solid black;width:200px;padding-left: 20px">
用戶名稱:<input v-model="insertUser.name"><br/>
用戶圖標:<input v-model="insertUser.iconUrl"><br/>
<img :src="insertUser.iconUrl"/>
<input type="button" @click="insert" value="保存">
</div>
<style>
.active {
display: none;
}
</style>
v-if="!isActive" 當數據變量isActive=false時顯示這個div 否則隱藏。
其他指令請參考官方api
2.2.3 樣式
2.2.3.1 樣式表
<div :class="{active:isActive}" v-if="!isActive" style="border:1px solid black;width:200px;padding-left: 20px">
用戶名稱:<input v-model="insertUser.name"><br/>
用戶圖標:<input v-model="insertUser.iconUrl"><br/>
<img :src="insertUser.iconUrl"/>
<input type="button" @click="insert" value="保存">
</div>
v-bind:class可以簡寫爲:class
:class="{樣式表名稱:條件}"
就是當vue數據isActive==true是 html中生成樣式表class=active,注意必須在style中定義.active
參考:https://cn.vuejs.org/v2/guide/class-and-style.html
2.2.3.2 內嵌樣式
export default {
data() {
return {
fontSizeVar:"20px"
}
}
}
<tr :style="{fontSize:fontSizeVar}">
<td>名稱</td>
<td>圖標</td>
<td>操作</td>
</tr>
:style={“css樣式名稱”:樣式值是獲取vue變量}
2.2.4 事件
export default {
mounted(){
console.log(axios.interceptors)
//直接調用AxiosPlugin插件install方法,該AxiosPlugin對象無論use多少次都只實例化一個對象 是單例的
//直接使用use來用的話 決定該插件是否使用。
//參考:https://www.jianshu.com/p/89a05706917a
Vue.use(AxiosPlugin)
//調用查詢
this.query()
},
methods: {
clear(){
for (var p in this.insertUser){
this.insertUser[p]=""
}
}
},
}
<input type="button" @click="isActive=false;ctype='insert';clear()" value="新增">
v-on:click可以簡寫爲@click,其他事件參考,去掉on。
vue其他語法參考
2.2.5 ajax
query(event) {
var dthis = this;
//鏈式調用承諾將來執行的then和catch是一個異步操作 叫做Promise
//axios.get("http://192.168.1.35/ums/tpauth/supportType1")返回就是一個Promise對象
axios.get("http://192.168.1.35/ums/tpauth/supportType").then(response => {
this.thirdList = response.data.data
}).catch(error=>{
Promise.reject(error);
})
}
axios語法參考
2.2.6 vue內置屬性
vm意思是View Model ,一般定義爲
var vm=new Vue({
el:'#app',
render: h => h(ThirdList)
})
一般一個vue項目在main.js定義的爲 root vm
其他所有vue控件類中export default都將是一個vm對象。
vm對象的官方解釋(https://cn.vuejs.org/v2/guide/instance.html)
<script>
export default {
data() {
return {
}
},
mounted(){},
methods: {}
}
</script>
生命週期圖譜
2.2.6.1 屬性
var vm = new Vue({
el:'#app',
data:{}, //數據
methods:{}, //方法調用
filters:{}, //私有過濾器
directives:{}, //私有指令
component:{}, //私有組件
beforeCreate(){}, // 在實例初始化之後,數據觀測 (data observer) 和 event/watcher 事件配置之前被調用。
created(){}, // 在實例創建完成後被立即調用。在這一步,實例已完成以下的配置:數據觀測 (data observer),屬性和方法的運算,watch/event 事件回調。然而,掛載階段還沒開始,$el 屬性目前不可見。
beforeMount(){}, // 在掛載開始之前被調用:相關的 render 函數首次被調用。
mounted(){}, //都能用了
beforeupdate(){}, //數據更新時調用,發生在虛擬 DOM 打補丁之前。這裏適合在更新之前訪問現有的 DOM,比如手動移除已添加的事件監聽器。
updated(){}, //當這個鉤子被調用時,組件 DOM 已經更新,
beforeDestroy(){}, //實例銷燬之前調用。在這一步,實例仍然完全可用。
destroyed(){} //Vue 實例銷燬後調用。調用後,Vue 實例指示的所有東西都會解綁定,所有的事件監聽器會被移除,所有的子實例也會被銷燬。
});
2.2.6.2 $refs屬性
在行上光標聚焦時高亮當前行,此時獲取當前行的dom元素,可以將tr上設置ref=當前行索引
<tr v-for="(r,index) in thirdList" :ref="'tr_'+index" :class="{o:index%2==0}" @mouseover="mouseover(index)" @mouseout="mouseout(index)">
<td>{{r.name}}</td>
<td><img :src="r.iconUrl"/></td>
<td><button @click="deleteUser(r)">刪除</button><button @click="isActive=false;ctype='update';insertUser.id=r.id;insertUser.name=r.name;insertUser.iconUrl=r.iconUrl">修改</button></td>
</tr>
光標懸浮和移出事件 (通過this.$refs[“名稱”]獲取dom元素的數組)
methods: {
mouseover(index){
var srcElement=this.$refs["tr_"+index][0];
srcElement.style.backgroundColor="red";
},
mouseout(index){
var srcElement=this.$refs["tr_"+index][0];
srcElement.style.backgroundColor="";
}
}
2.2.6.3 $attrs和$props屬性
vue的父子組件傳值的時候,我們先需要的子組件上用props註冊一些屬性:
<template>
<div>
props:{{name}},{{age}} 或者 {{$props['name']}},{{$props['age']}}
</div>
</template>
export default{
props: ['name','age']
}
然後父組件調用的時候當屬性來傳值
<child name="rick" :age="當前vm中data數據"></child>
如果我們給child傳props沒有註冊的屬性gender,我們就要用$attrs來取了
<child name="rick" :age="18" gender="male"></child>
child:
<template>
<div>
props:{{name}},{{age}} 或者 {{$props['name']}},{{$props['age']}}
<br>
attrs: {{$attrs['gender']}} 在$attrs裏面只會有props沒有註冊的屬性
</div>
</template>
export default{
props: ['name','age']
}
2.2.6.4 $route和$router屬性
- router是VueRouter的一個對象,通過Vue.use(VueRouter)和VueRouter構造函數得到一個router的實例對象,
這個對象中是一個全局的對象,他包含了所有的路由包含了許多關鍵的對象和屬性。 - route是一個跳轉的路由對象,每一個路由都會有一個route對象,是一個局部的對象,可以獲取對應的name,path,params,query等
對應值就是當前路徑對應的路由。
2.2.6.5 vm.$parent和vm.$root和vm.$children
- vm.$root :獲取當前vm對象的根vm對象 ,一般root就是main.js中new
Vue的那個
this.$root.$options
{components: {…}, directives: {…}, filters: {…}, _base: ƒ, el: "#app", …}
- vm.$parent :獲取當前vm對象的父vm對象 ,有父子控件的可以獲取父vm。
- vm.$children :獲取當前vm對象的所有子vm對象。
如果需要查看vue控件的父子關係,可以使用瀏覽器安裝vue-devtools插件,如果檢測到vue項目,多一個vue面板
2.2.6.6 $store
VueX 是一個專門爲 Vue.js
應用設計的狀態管理架構,統一管理和維護各個vue組件的可變化狀態(你可以理解成
vue 組件裏的某些 data )。 Vue有五個核心概念,state, getters, mutations,
actions, modules。本文將對這個五個核心概念進行梳理。
- state => 基本數據
- getters => 從基本數據派生的數據
- mutations => 提交更改數據的方法,同步!
- actions => 像一個裝飾器,包裹mutations,使之可以異步。
- modules => 模塊化Vuex
簡單案例:
初始化store
const store = new Vuex.Store({
state: {
count:0
}
})
const app = new Vue({
el:"#app"
store,
router,
render: h => h(App)
})
任何vm中可以直接應用
{{this.$store.state.count}}
具體詳細參考官網
2.2.6.x 其他$屬性
-
vm.$el:獲取vm對象關聯的DOM元素;
-
vm.$data:獲取Vue實例的data選項(對象)
-
vm.options.methods,獲取Vue實例的自定義屬性methods)
-
vm.$mount方法是在dom上掛載我們的擴展.
var judy = Vue.extend({
template:'<p>{{message}}</p>',
data: function () {
return{
message:'I am Jiaozi'
}
}
});
var vm = new judy().$mount('#app')
<div id="app">
{{message}}
</div>
打印結果:
<p>I am Jiaozi</p>
其他方法比如 $watch $once $emit 參考官方api
其他屬性參考(https://cn.vuejs.org/v2/api/#%E5%AE%9E%E4%BE%8B%E5%B1%9E%E6%80%A7)