http://www.cnblogs.com/-ding/p/6339740.html
①簡單來說:
就是幾個組件放在一個掛載點下,然后根據父組件的某個變量來決定顯示哪個,或者都不顯示。
②動態切換:
在掛載點使用component標簽,然后使用v-bind:is=”組件名”,會自動去找匹配的組件名,如果沒有,則不顯示;
改變掛載的組件,只需要修改is指令的值即可。
如示例代碼:
- <div id="app">
- <button @click="toshow">點擊讓子組件顯示</button>
- <component v-bind:is="which_to_show"></component>
- </div>
- <script>
- var vm = new Vue({
- el: '#app',
- data: {
- which_to_show: "first"
- },
- methods: {
- toshow: function () { //切換組件顯示
- var arr = ["first", "second", "third", ""];
- var index = arr.indexOf(this.which_to_show);
- if (index < 3) {
- this.which_to_show = arr[index + 1];
- } else {
- this.which_to_show = arr[0];
- }
- }
- },
- components: {
- first: { //第一個子組件
- template: "<div>這里是子組件1</div>"
- },
- second: { //第二個子組件
- template: "<div>這里是子組件2</div>"
- },
- third: { //第三個子組件
- template: "<div>這里是子組件3</div>"
- },
- }
- });
- </script>
說明:
點擊父組件的按鈕,會自動切換顯示某一個子組件(根據which_to_show這個變量的值來決定)。
③keep-alive
簡單來說,被切換掉(非當前顯示)的組件,是直接被移除了。
在父組件中查看this.$children屬性,可以發現,當子組件存在時,該屬性的length為1,而子組件不存在時,該屬性的length是0(無法獲取到子組件);
假如需要子組件在切換后,依然需要他保留在內存中,避免下次出現的時候重新渲染。那么就應該在component標簽中添加keep-alive屬性。
如代碼:
- <div id="app">
- <button @click="toshow">點擊讓子組件顯示</button>
- <component v-bind:is="which_to_show" keep-alive></component>
- </div>
- <script>
- var vm = new Vue({
- el: '#app',
- data: {
- which_to_show: "first"
- },
- methods: {
- toshow: function () { //切換組件顯示
- var arr = ["first", "second", "third", ""];
- var index = arr.indexOf(this.which_to_show);
- if (index < 3) {
- this.which_to_show = arr[index + 1];
- } else {
- this.which_to_show = arr[0];
- }
- console.log(this.$children);
- }
- },
- components: {
- first: { //第一個子組件
- template: "<div>這里是子組件1</div>"
- },
- second: { //第二個子組件
- template: "<div>這里是子組件2</div>"
- },
- third: { //第三個子組件
- template: "<div>這里是子組件3</div>"
- },
- }
- });
- </script>
說明:
初始情況下,vm.$children屬性中只有一個元素(first組件),
點擊按鈕切換后,vm.$children屬性中有兩個元素,
再次切換后,則有三個元素(三個子組件都保留在內存中)。
之后無論如何切換,將一直保持有三個元素。