2019-01-29 vue組件基礎(chǔ)篇1

組件

  1. 全局注冊(cè)組件

import Vue from 'vue'
Vue.component('ceshi', {
    template: '<button v-on:click="counter += 1">{{ counter }}</button>',
    data() { 
          return { counter: 0 }
    }
})
export default {}

那個(gè)組件需要使用就直接添加使用
<ceshi></ceshi>
  1. 局部注冊(cè)組件

var child = {
  template: '<button>測(cè)試</button>'
}
export default {
  components: {
    'ceshi':child
  }
}
  1. 父組件向子組件傳遞數(shù)據(jù) props

【3.1】props的值可以是兩種,一種是字符串?dāng)?shù)組,一種是對(duì)象

<div id="app">
    <ceshi msg="來(lái)自父組件的數(shù)據(jù)"></ceshi>
</div>

Vue.component('ceshi', {
    props: ['msg'],
    template: '<div>{{ msg }}</div>',
})

var app = new Vue({
    el: '#app'
})

【3.2】由于HTML特性不區(qū)分大小寫(xiě),當(dāng)使用DOM模板時(shí),駝峰命名(camelCase)的props名稱要轉(zhuǎn)為短橫分隔命名(kebab-case)

<div id="app">
    <ceshi camel-case="提示信息"></ceshi>
</div>

Vue.component('ceshi', {
    props: ['camelCase'],
    template: '<div>{{ camelCase}}</div>',
})

var app = new Vue({
    el: '#app'
})

【3.3】這里用v-model綁定了父級(jí)的數(shù)據(jù)parentMessage,當(dāng)通過(guò)輸入框任意輸入時(shí),子組件接收到的props "message"也會(huì)實(shí)時(shí)響應(yīng),并且更新組件模板。

<div id="app">
    <input type="text" v-model="parentMessage">
    <ceshi :message="parentMessage"></ceshi>
</div>

Vue.component('ceshi', {
    props: ['message'],
    template: '<div>{{ message }}</div>',
})

var app = new Vue({
    el: '#app',
    data: {
        parentMessage: ''
    }
})

【3.4】有時(shí)候,傳遞的數(shù)據(jù)并不是直接寫(xiě)死的,而是來(lái)自父級(jí)的動(dòng)態(tài)數(shù)據(jù),這時(shí)可以使用指令v-bind來(lái)動(dòng)態(tài)綁定props的值,當(dāng)父組件的數(shù)據(jù)變化時(shí),也會(huì)傳遞給子組件

<div id="app">
    <ceshi message="[1,2,3]"></ceshi>
    <ceshi :message="[1,2,3]"></ceshi>
</div>
<script>
    Vue.component('ceshi',{
        props: ['message'],
        template: '<div>{{ message.length }}</div>'
    });
    var app = new Vue({
        el: '#app'
    })
</script>

注意,如果你要直接傳遞數(shù)字、布爾值、數(shù)組、對(duì)象。而且不使用v-bind,傳遞的僅僅是字符串,如上。同一個(gè)組件使用了兩次,區(qū)別僅僅是第二個(gè)使用的是v-bind。渲染后的結(jié)果,第一個(gè)是7,第二個(gè)才是數(shù)組的長(zhǎng)度3。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 組件(Component)是Vue.js最核心的功能,也是整個(gè)架構(gòu)設(shè)計(jì)最精彩的地方,當(dāng)然也是最難掌握的。...
    六個(gè)周閱讀 5,770評(píng)論 0 32
  • 1.安裝 可以簡(jiǎn)單地在頁(yè)面引入Vue.js作為獨(dú)立版本,Vue即被注冊(cè)為全局變量,可以在頁(yè)面使用了。 如果希望搭建...
    Awey閱讀 11,298評(píng)論 4 129
  • 這篇筆記主要包含 Vue 2 不同于 Vue 1 或者特有的內(nèi)容,還有我對(duì)于 Vue 1.0 印象不深的內(nèi)容。關(guān)于...
    云之外閱讀 5,177評(píng)論 0 29
  • 前言 您將在本文當(dāng)中了解到,往網(wǎng)頁(yè)中添加數(shù)據(jù),從傳統(tǒng)的dom操作過(guò)渡到數(shù)據(jù)層操作,實(shí)現(xiàn)同一個(gè)目標(biāo),兩種不同的方式....
    itclanCoder閱讀 26,244評(píng)論 1 12
  • Vue 實(shí)例 屬性和方法 每個(gè) Vue 實(shí)例都會(huì)代理其 data 對(duì)象里所有的屬性:var data = { a:...
    云之外閱讀 2,373評(píng)論 0 6

友情鏈接更多精彩內(nèi)容