基本結(jié)構(gòu)
new Vue({
data:{//用于綁定數(shù)據(jù)
a:1,
b:[]
},
methods:{//用于綁定的方法
doSomething:function(){
this.a++;
}
},
watch:{//用于監(jiān)聽數(shù)據(jù)變化
'a':function(new,old){
console.log(new,old)
}
},
computed:{//用于計算數(shù)據(jù)
myValueWithoutNumber() {
return this.myValue.replace(/\d/g,'')
}
},
})
源生指令
v-text指定節(jié)點文本
v-html指定html格式并解析
v-show隱藏,利用display
v-if隱藏,直接銷毀節(jié)點
v-else前面必須有v-if v-else-if
v-for="item in arr" {{item}}變量
v-for="(item,index) in arr" {{index}}角標(biāo)
v-for="(val,key,index) in obj" 值,鍵,角標(biāo) 遍歷對象
加上:key="item" 提高效率
v-on事件綁定
v-bind屬性綁定
v-model數(shù)據(jù)綁定,一般用于input
checkbox綁定多個:value可修改數(shù)組
修飾符:.number .trim .lazy
v-once只綁定一次
v-pre不解析
綁定事件
//只觸發(fā)一次使用v-once
<button v-on:click="doThis"></button>
<button @click="doThis"></button>
methods:{
doThis:function(){
}
}
數(shù)據(jù)渲染
<p>{{a}}</p>
<p v-text="a"></p><!--格式處理-->
<p v-html="a"></p><!--格式保存-->
new Vue({
data:{
a:1,
b:[]
}
})
//強制渲染函數(shù)
app.$forceUpdate()
控制隱藏
<p v-if="isShow"></p><!--直接刪除標(biāo)簽-->
<p v-show="isShow"></p><!--通過display屬性渲染-->
new Vue({
data:{
isShow:true;
}
})
渲染循環(huán)
<ul>
<li v-for='item in items'>
<p v-text='item.label'></p>
</li>
</ul>
data:{
item:[
{
label:'apple'
},
{
lable:'banana'
}
]
},
數(shù)據(jù)綁定
<img v-bind:src="imageSrc">
<img :src="imageSrc"><!--簡寫形式-->
<div :class="{red:isRed}"></div><!--當(dāng)isRed為true時,將類名設(shè)置為red-->
<div :class="[classA,classB]"></div>
<div :class="[classA,{classB:isB,classC:isC}]"></div>
<a :href="link"></a>
data(){
return{
link:https://www.baidu.com
}
}
<!--各種類型表單演示-->
<select v-model="mySelection">
<option v-for="item in selectOption" :value="item.value">{{item.name}}</option>
</select>
{{mySelection}}
<input v-model="myRadio" type="radio" value="apple"/>
<input v-model="myRadio" type="radio" value="banana"/>
{{myRadio}}
<input v-model.lazy="myValue" type="text" /><!--trim,number-->
{{myValue}}
<input type="checkbox" v-model="myCheckBox" v-for="item in boxex" :value="item"/>
{{myCheckBox}}
data() {
return {
selection:'',
selectOption:[
{
name:'apple',
value:0
},
{
name:'banana',
value:1
}
],
boxex:['apple','banana'],
myRadio:'',
myValue:'',
myCheckBox:[]
};
},
{{false ? 'a':'b'}}//b
v-html="<span>123</span>"http://123
綁定style會給根據(jù)瀏覽器自動加前綴
app.$set(app.obj,'a',1)
app.$delelte(app.obj,'a',1)
引入組件
import comA from './components/a'<!--導(dǎo)入-->
export default{
components:{comA}<!--注冊-->
}
組件間通信
<!--父組件:-->
<com-a @my-event="onComaMyEvent"></com-a><!--聲明my-event事件,并綁定onComaMyEvent方法-->
<script>
import comA from "./components/a"
export default {//導(dǎo)入并注冊
components:{comA},
methods:{
onComaMyEvent(param) {
console.log('on my comA'+param)
}
}
}
</script>
<!--子組件:-->
<button @click="emitMyEvent"></button>
methods:{
emitMyEvent() {
this.$emit('my-event',this.hello)<!--通過$emit方法傳值-->
}
}
計算屬性
//自帶緩存
<!--便與實現(xiàn)復(fù)雜功能-->
<input type="text" v-model="myValue"/>
{{myValueWithoutNumber}}
computed:{
myValueWithoutNumber() {
return this.myValue.replace(/\d/g,'')
}
},
<!--或(通過調(diào)用方法實現(xiàn)實時更新)-->
<input type="text" v-model="myValue"/>
{{getMyValueWithoutNumber}}
methods:{
getMyValueWithoutNumber() {
return this.myValue.replace(/\d/g,'')
}
},
通過$(this.val)獲取
監(jiān)聽器
<input type="text" v-model="myValue"/>
watch:{
myValue:function (val,old) {
console.log(val,old)
}
},
handle (){},immediate:true//會讓方法初始化時執(zhí)行一次
deep:true//false時,沒有引用時改變對象的屬性不會觸發(fā),或者監(jiān)聽obj.a
父子組件通信
子————>父(通過觸發(fā)emit事件)
父————>子(通過屬性傳遞)
<!--1. 父組件:-->
<input type="text" v-model="myValue"/>
<!--動態(tài)綁定myValue屬性,傳遞給子組件,并在觸發(fā)my-event事件時調(diào)用getMyEvent方法-->
<com-a :my-value="myValue" @my-event="getMyEvent"></com-a>
methods:{
getMyEvent(hello) {<!--接收子組件傳遞的參數(shù)-->
console.log('i got my event'+hello)
}
}
<!-- 2. 子組件-->
{{myValue}}<!--接收父組件屬性myValue-->
<button @click="emitMyEvent"></button>
props:{
'my-value':[Number,String]<!--注冊父屬性my-value,并指定參數(shù)的數(shù)據(jù)類型-->
},
data() {
return {
hello: 'i am a component a '
}
},
methods:{
emitMyEvent() {
<!--$emit方法用于將子組件的數(shù)據(jù)傳遞給父組件中的my-event事件,將hello數(shù)據(jù)傳遞給父組件-->
this.$emit('my-event',this.hello)
}
}
插槽功能
<!--父組件:-->
<com-a>
<!--將模板插到對應(yīng)的子組件標(biāo)簽里-->
<p slot="header">header</p>
<p slot="footer">footer</p>
</com-a>
<!--子組件:-->
<!--slot標(biāo)簽接收模板-->
<slot name="header"></slot>
<slot>XXX</slot>
<slot name="footer"></slot>
//作用域插槽
<slot aaa="123" bbb="456"></slot>
//在被引用元素中獲取到插槽屬性
<span slot-scope="props">{{props.aaa + props.bbb}}</slot>
//組件溝通
privide(){}和inject(){}
Object.defineprojerty的get方法
動態(tài)組件
<!--通過改變currentView實現(xiàn)動態(tài)加載組件-->
<keep-alive><!--keep-alive將之前的組件緩存起來,提高組件切換速度-->
<p :is="currentView"></p>
</keep-alive>
動畫
<!--若標(biāo)簽名相同會出bug,通過屬性key="XXX"區(qū)分-->
<button @click="show = !show">Toggle</button>
<div class="ab">
<transition name="fade" mode="out-in"><!--通過transition標(biāo)簽實現(xiàn)-->
<p v-show="show">i am show</p>
</transition>
</div>
<!--淡入淡出-->
<style>
.fade-enter-active,.fade-leave-active{
transition: opacity .5s ease-out;
}
.fade-enter,.fade-leave-active{
opacity: 0;
}
</style>
路由
<!-- main.js -->
import VRouter from 'vue-router'<!-- 導(dǎo)入路由組件 -->
import Apple from './components/apple'<!-- 導(dǎo)入兩個組件 -->
import Banana from './components/banana'
Vue.use(VRouter)<!-- 注冊 -->
let router = new VRouter({
mode:'history',//去掉url中的#號
//base: '/base/'// 基路徑為/base/
// linkActiveClass: 'active link', //被激活的路徑會添加class
// linkExactActiveClass: 'exact link',//被完全激活的路徑添加class
scrollBehavior (to, from, savedPosition){
//返回時頁面處于用戶之前所停留的位置
if (savedPosition) {
return savedPosition
} else {
return { x:0, y:0 }
}
},
fallback: true //當(dāng)瀏覽器不支持跳轉(zhuǎn)時開啟多頁模式
routes: [
{
<!-- :后面為參數(shù)傳給指定組件 -->
path: '/apple/:color/detail/:type',
props: true,//直接把參數(shù)傳到子組件中的props中
component:Apple,
name:'applePage',<!-- 自定義命名 -->
meta: {
title: 'this is app',
description: '123'
},
children:[<!-- 子路由 -->
{
path:'red',<!-- tp://localhost:8080/apple/red -->
component:RedApple
}
]
},{
path: '/banana',
component:Banana
}
]
});
new Vue({
el: '#app',
router,<!-- 將上面配置的router實例化 -->
render:function (h) {
return h(App);
}
})
<!-- 在Apple組件中,用內(nèi)置對象$route.params接收參數(shù)Json對象 -->
<!-- App.vue -->
<router-view></router-view><!-- 內(nèi)置組件 -->
//router-link 本身是一個a標(biāo)簽
<router-link :to="{path:'/apple',params:{color:'yellow'}}">to apple</router-link><!-- 或把path:'/apple'替換為name:'applePage' -->
<router-link to="/banana">to banana</router-link>
<router-link :to="{path:'/apple/red'}">to apple red</router-link>
<!-- 命名路由 -->
routes: [
{
path: '/apple',
component:{
ViewA:Apple,
ViewB:RedApple
}
},
{
path: '/banana',
component:Banana
}
]
<!-- App.vue中 -->
<router-view name="viewA"></router-view>
<router-view name="viewB"></router-view>
<!-- 重定向 -->
routes: [
{<!-- 將根目錄重定向到/apple -->
path:'/',
redirect:'/apple'
},
]
通過this.$route獲取到全部路徑信息
//webpack.config.client.js 配置刷新路徑
historyApiFallback: {
index: 'index.html'
}
狀態(tài)管理
組件-->actions-->Mutations-->State
<!-- main.js中引入Vuex -->
import Vuex from 'vuex'
Vue.use(Vuex)<!-- 注冊 -->
let store = new Vuex.Store({
state:{<!-- 保存狀態(tài) -->
totalPrice:0
},
getters:{<!-- 將狀態(tài)封裝 -->
getTotal(state) {
return state.totalPrice
}
},
mutations:{<!-- 減少兩個方法 -->
increment(state,price) {
state.totalPrice += price
},
decrement(state,price) {
state.totalPrice -= price
}
}
})
new Vue({
el: '#app',
store<!-- 實例化,在子組件中通過this.$store.state.commit調(diào)用 -->
})
<!-- App.vue -->
<template>
<div>
{{totalPrice}}
<apple></apple>
<banana></banana>
</div>
</template>
<script>
import Apple from './components/apple'
import Banana from './components/banana'
export default {
components:{
Apple,Banana
},
computed:{
totalPrice() {/* 通過封裝的getters獲取狀態(tài)中的總價 */
return this.$store.getters.getTotal
}
},
}
</script>
<!-- Apple組件中 -->
methods: {
addOne() {<!-- 通過commit方法,來觸發(fā)mutations中的方法,并傳入調(diào)用的方法名和參數(shù) -->
this.$store.commit('increment', this.price)
},
minuOne() {
this.$store.commit('decrement', this.price)
}
}
<!-- 通過action觸發(fā)mutations -->
<!-- main.js -->
mutations:{
increment(state,price) {
state.totalPrice += price
},
decrement(state,price) {
state.totalPrice -= price
}
},
actions:{<!-- 只能調(diào)用mutations里面的方法 -->
increase(context,price) {
context.commit('increment',price)
}
}
<!-- 在Apple組件中這樣調(diào)用-->
addOne() {
<!-- dispatch 專門用來觸發(fā)action -->
this.$store.dispatch('increase', this.price)
},
總結(jié): 1. 異步修改store數(shù)據(jù)的情況下,使用action
2.同步的情況下使用mutation
vue-resource(ajax)
import VueResource from 'vue-resource'
Vue.use(VueResource)//注冊插件
//在頁面初始化時
created:function(){
this.$http.get('getList').then(//POST:post('getList',{userId:123})
function(data) {
console.log(data)
},function(err) {
console.log(err)
}
)
},
生命周期
beforeCreate(){},//初始化一定會執(zhí)行,
create(){},//初始化完畢執(zhí)行
beforeMount(){},//掛載到頁面才會執(zhí)行,由最外層節(jié)點調(diào)用,其他方法
mounted(){},//掛載完畢執(zhí)行
beforeUpdate(){},//每次有數(shù)據(jù)更新才會執(zhí)行
updated(){},//更新完畢執(zhí)行
activated(){},
deactivated(){},
beforeDestroy(){},//Vue實例被銷毀時執(zhí)行
destroyed(){},//銷毀后執(zhí)行
errorCaptured(){}//向上冒泡,收集錯誤信息
定義組件
Vue.component('CompOne',component)//定義全局組件,駝峰命名,類似于Java類
components:{ CompOne: component},
<comp-one></comp-one>//自動轉(zhuǎn)為-形式
非new Vue形式的組件,定義data屬性:
data () {
return {
text: 123
}
}
props: {//從父組件傳進(jìn)來的屬性
active: Boolean
}
<comp-one :active="true"></comp-one>
在子組件調(diào)用this.$parent.text改變父組件的數(shù)據(jù)
組件間數(shù)據(jù)雙向綁定
import Vue from 'vue'
const component = {
model: {
prop: 'value1',
event: 'change'
},
props: ['value1'],
template: `
<div>
<input type="text" @input="handleInput" :value="value1">
</div>
`,
methods: {
handleInput (e) {
this.$emit('change', e.target.value)
}
}
}
new Vue({
components: {
CompOne: component
},
el: '#root',
data () {
return {
value: '123'
}
},
template: `
<div>
<comp-one v-model="value"></comp-one>
</div>
`
})
如果你想把一個對象的所有屬性作為 prop
進(jìn)行傳遞,可以使用不帶任何參數(shù)的 v-bind (即用
v-bind 而不是 v-bind:prop-name)夭咬。例如盯质,已知一個todo 對象:
todo: {
text: 'Learn Vue',
isComplete: false
}
然后:
<todo-item v-bind="todo"></todo-item>
將等價于:
<todo-item
v-bind:text="todo.text"
v-bind:is-complete="todo.isComplete"
></todo-item>
自定義事件
使用 $on(eventName) 監(jiān)聽事件
使用 $emit(eventName, optionalPayload) 觸發(fā)事件
父組件可以在使用子組件的地方直接用 v-on 來監(jiān)聽子組件觸發(fā)的事件框咙。
Table屬性
在el-table中聲明slot-scope="scope",單行中使用scope.row獲取某行的屬性
//把數(shù)組里符合條件的數(shù)據(jù)篩選出來
this.tableData = this.tableData.filter(o=>o.goods.goodsId!=goods.goodsId);
//固定表頭
只要在el-table元素中定義了height屬性餐胀,即可實現(xiàn)固定表頭的表格咽筋,而不需要額外的代碼。
//固定一列
固定列需要使用fixed屬性爱沟,它接受 Boolean 值或者leftright帅霜,表示左邊固定還是右邊固定。
//多級表頭
只需要在 el-table-column 里面嵌套 el-table-column呼伸,就可以實現(xiàn)多級表頭身冀。
//展開行
通過設(shè)置 type="expand" 和 Scoped slot 可以開啟展開行功能,el-table-column 的模板會被渲染成為展開行的內(nèi)容,展開行可訪問的屬性與使用自定義列模板時的 Scoped slot 相同搂根。