1.組件
全局組件注冊、局部組件注冊、父子雙向傳遞值、動態組件、slot內容分發、data、$refs
(1)配置子組件
components:{ "my-component3":{ template:"<h3>這是子組件</h3>" } }
var myComponent4 = Vue.extend({
template :`<h4> 第四個組件{{msg}} <h4>`
})
(2)在vue中組件的作用域是隔離的,如果想要在子組件中訪問父級的數據,則需要父級顯式的向下傳遞
為了解決地址傳遞的問題,在組件中聲明data必須為函數
且返回一個新對象,這樣每個組件用到的data是一塊新的內存地址,組件間互不影響
return {
num:0
}
}```
`data:{ num:0 }`
如果需要獲取dom元素,可將元素以 ref ="name" 進行標識
通過this.$refs.name 得到對應的name的dom,盡量少用
` this.$refs.mi.focus();`
(3)組件動態切換
通過component聲明動態組件,綁定is決定渲染哪個子組件,is所綁定的值,必須在component中主頁
通過keep-alive標簽包裹 component 標簽,使組件保留在內存中,重新切換時,將不再重新渲染
在1.x版本中,keep-alive是component的一個屬性<component keep-alive></component>
<button @click="currentView='home'"> 首頁 </button>
<button @click="currentView='cart'"> 購物車 </button>
<button @click="currentView='mine'"> 個人中心 </button>
<keep-alive>
<component :is="currentView"></component>
</keep-alive>
var vm = new Vue({
el: ".box",
data: {
currentView : "home"
},
components: {
home : {
template : <h1>首頁{cjfntpf}</h1>
,
data :function(){
return {
d:new Date().getTime()
}
}
},
cart : {
template : <h1>購物車</h1>
},
mine : {
template : <h1>個人中心</h1>
}
},
methods:{
}
})
(4)slot
`<slot></slot>`插槽(內容分發)
有name屬性的標簽叫 具名插槽 `<slot name='a'></slot>`
沒有name屬性的標簽叫 匿名插槽
在組件渲染模板時,會拋棄標簽內的原始內容,為了保留原始內容,可以在 模板 內通過 slot 標簽預留插槽位
原始內容(不含slot屬性的)會默認放到匿名的插槽內
含有slot屬性的,會去查找對應的插槽,未找到,將拋棄內容