Vue學(xué)習(xí)總結(jié)

基本結(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 相同搂根。

render function

image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末蝶怔,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子兄墅,更是在濱河造成了極大的恐慌,老刑警劉巖澳叉,帶你破解...
    沈念sama閱讀 217,277評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件隙咸,死亡現(xiàn)場離奇詭異,居然都是意外死亡成洗,警方通過查閱死者的電腦和手機五督,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評論 3 393
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來瓶殃,“玉大人充包,你說我怎么就攤上這事∫4唬” “怎么了基矮?”我有些...
    開封第一講書人閱讀 163,624評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長冠场。 經(jīng)常有香客問我家浇,道長,這世上最難降的妖魔是什么碴裙? 我笑而不...
    開封第一講書人閱讀 58,356評論 1 293
  • 正文 為了忘掉前任钢悲,我火速辦了婚禮,結(jié)果婚禮上舔株,老公的妹妹穿的比我還像新娘莺琳。我一直安慰自己,他們只是感情好载慈,可當(dāng)我...
    茶點故事閱讀 67,402評論 6 392
  • 文/花漫 我一把揭開白布惭等。 她就那樣靜靜地躺著,像睡著了一般办铡。 火紅的嫁衣襯著肌膚如雪咕缎。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,292評論 1 301
  • 那天料扰,我揣著相機與錄音凭豪,去河邊找鬼。 笑死晒杈,一個胖子當(dāng)著我的面吹牛嫂伞,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 40,135評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼帖努,長吁一口氣:“原來是場噩夢啊……” “哼撰豺!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起拼余,我...
    開封第一講書人閱讀 38,992評論 0 275
  • 序言:老撾萬榮一對情侶失蹤污桦,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后匙监,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體凡橱,經(jīng)...
    沈念sama閱讀 45,429評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,636評論 3 334
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片贝润。...
    茶點故事閱讀 39,785評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡妈倔,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 35,492評論 5 345
  • 正文 年R本政府宣布巡李,位于F島的核電站,受9級特大地震影響扶认,放射性物質(zhì)發(fā)生泄漏击儡。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,092評論 3 328
  • 文/蒙蒙 一蝠引、第九天 我趴在偏房一處隱蔽的房頂上張望阳谍。 院中可真熱鬧,春花似錦螃概、人聲如沸矫夯。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽训貌。三九已至,卻和暖如春冒窍,著一層夾襖步出監(jiān)牢的瞬間递沪,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評論 1 269
  • 我被黑心中介騙來泰國打工综液, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留款慨,地道東北人。 一個月前我還...
    沈念sama閱讀 47,891評論 2 370
  • 正文 我出身青樓谬莹,卻偏偏與公主長得像檩奠,于是被迫代替她去往敵國和親桩了。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,713評論 2 354

推薦閱讀更多精彩內(nèi)容