【Vue】vue元件的切換與插槽

:is、slot

【Vue】vue元件的切換與插槽

:is、slot


動態切換元件

  • 使用 v-if 判斷。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// <-----html----->
#app
  button(@click="a = 'apple'" :key="a") 按鈕A
  button(@click="a = 'banana'" :key="a") 按鈕B
  hr
  div(is="apple" v-if="a === 'apple'")
  div(is="banana" v-if="a === 'banana'")

script(type="text/x-template" id="apple")
  p 蘋果
  
script(type="text/x-template" id="banana")
  p 香蕉

// <-----js----->
Vue.component("apple",{
  template: "#apple",
});

Vue.component("banana",{
  template: "#banana"
});

var app = new Vue({
  el: "#app",
  data:{
    a: "apple"
  }
});

  • 使用 :is 判斷。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// <-----html----->
#app
  button(@click="a = 'apple'" :key="a") 按鈕A
  button(@click="a = 'banana'" :key="a") 按鈕B
  hr
  div(:is="a")

script(type="text/x-template" id="apple")
  p 蘋果
  
script(type="text/x-template" id="banana")
  p 香蕉

// <-----js----->
Vue.component("apple",{
  template: "#apple",
});

Vue.component("banana",{
  template: "#banana"
});

var app = new Vue({
  el: "#app",
  data:{
    a: "apple"
  }
});


匿名插槽

  • 使用<slot>讓標籤內容能被替換。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// <-----html----->
#app
  list-com 
    li 芭樂
  
script(type="text/x-template" id="list-com")
  ul
    li 蘋果
    slot 香蕉
    li 鳳梨

// <-----js----->
Vue.component("list-com",{
  template: "#list-com",
});

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

// <-----結果----->
//.蘋果
//.芭樂
//.鳳梨

  • 如果都使用<slot>標籤內容都會被替換。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// <-----html----->
#app
  list-com 
    li 芭樂
  
script(type="text/x-template" id="list-com")
  ul
    slot 蘋果
    slot 香蕉
    slot 鳳梨

// <-----js----->
Vue.component("list-com",{
  template: "#list-com",
});

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

// <-----結果----->
//.芭樂
//.芭樂
//.芭樂


具名插槽

  • 新增[name]屬性[自訂值],對應[slot]屬性[自訂值]。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// <-----html----->
#app
  list-com 
    li(slot="a") 芭樂
  
script(type="text/x-template" id="list-com")
  ul
    slot 蘋果
    slot(name="a") 香蕉
    slot 鳳梨

// <-----js----->
Vue.component("list-com",{
  template: "#list-com",
});

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

// <-----結果----->
//.蘋果
//.芭樂
//.鳳梨

若不想讓元件的標籤被取代,可以使用<template>

vue 

其他相關