vue中動態元件和非同步元件
阿新 • • 發佈:2021-01-06
技術標籤:vue
......
<script>
/*
動態元件:
動態元件語法--固定元件名 component,會接收is屬性引數,由is屬性對應的值判斷顯示哪個元件
動態元件--根據資料的變化,結合component標籤,來隨時動態切換元件的顯示
keep-alive -- 快取標籤
動態元件和keep-alive一般會一起使用
非同步元件:非同步執行某些元件的邏輯
暫時掌握其語法即可
*/
const app = Vue.createApp( {
template: `
<keep-alive>
<component :is='currentItem'/>
</keep-alive>
<br/>
測試
<button @click='handleClick'>切換</button>
<br/>
<async-common-item/>
`,
data () {
return {
currentItem:'input-item'
}
},
methods: {
handleClick() {
this.currentItem = this.currentItem==='input-item'?'common-item':'input-item'
}
}
})
app.component('input-item',{
data(){
return{
}
},
template:`
<div>
<input/>
</div>
`,
methods:{
handleClick(){
console.log('測試中')
}
}
})
app.component('common-item',{
data(){
return{
}
},
template:`
<div>
<div>common-item</div>
</div>
`,
methods:{
handleClick(){
console.log('測試中')
}
}
})
/* 註冊非同步元件 */
app.component('async-common-item',Vue.defineAsyncComponent(()=>{
return new Promise((resolve,reject)=>{
setTimeout(()=>{
resolve({
template:'<div>非同步成功</div>'
})
},4000)
})
}))
/* 注意:使用元件時需要先註冊完元件再將該vue例項掛載到root元素上 */
/* vm代表的就是vue應用的根元件
vm獲取根節點上資料,呼叫data時,data前加一個$,操作vm時,資料改變,檢視也會自動發生改變
如果該資料是根資料,也可以直接vm. 呼叫
*/
const vm = app.mount('#root')
//app.unmount()//讓vue失效
</script>
......