<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="./vue.js"></script>
<!-- <script src="http://cdn.staticfile.org/vue/2.6.10/vue.common.dev.js"></script> -->
</head>
<body>
<div id="root">
<child-one v-if="type == 'child-one'"></child-one>
<child-two v-if="type == 'child-two'"></child-two>
<button @click="handleButtonClick">change</button>
</div>
<script type="text/javascript">
Vue.component("child-one", {
template: `<div>child-one</div>`
});
Vue.component("child-two", {
template: `<div>child-two</div>`
});
var vm = new Vue({
el: "#root",
data: {
type: "child-one"
},
methods: {
handleButtonClick: function() {
this.type = (this.type == "child-one" ? "child-two" : "child-one");
}
}
})
</script>
</body>
</html>
同樣的效果,使用動態組件(點擊切換會銷燬一個組件,創建另一個組件。很顯然,這樣對性能是有損耗的):
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="./vue.js"></script>
<!-- <script src="http://cdn.staticfile.org/vue/2.6.10/vue.common.dev.js"></script> -->
</head>
<body>
<div id="root">
//當然還可以用動態組件的方式(vue自帶的標籤,它指的就是一個動態組件)。動態組件的意思是:它會根據:is裏面數據的變化自動加載不同的組件:
<component :is="type"></component>
<button @click="handleButtonClick">change</button>
</div>
<script type="text/javascript">
Vue.component("child-one", {
template: `<div>child-one</div>`
});
Vue.component("child-two", {
template: `<div>child-two</div>`
});
var vm = new Vue({
el: "#root",
data: {
type: "child-one"
},
methods: {
handleButtonClick: function() {
this.type = (this.type == "child-one" ? "child-two" : "child-one");
}
}
})
</script>
</body>
</html>
爲了解決頻繁銷燬-創建,可以用v-once(因爲這個v-once,在切換的時候會把要銷燬的這個放內存裏了。也就是不需要創建了,直接從內存裏拿)
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="./vue.js"></script>
<!-- <script src="http://cdn.staticfile.org/vue/2.6.10/vue.common.dev.js"></script> -->
</head>
<body>
<div id="root">
<!-- <child-one v-if="type == 'child-one'"></child-one>
<child-two v-if="type == 'child-two'"></child-two> -->
//當然還可以用動態組件的方式(vue自帶的標籤,它指的就是一個動態組件)。動態組件的意思是:它會根據:is裏面數據的變化自動加載不同的組件:
<component :is="type"></component>
<button @click="handleButtonClick">change</button>
</div>
<script type="text/javascript">
Vue.component("child-one", {
template: `<div v-once>child-one</div>`
});
Vue.component("child-two", {
template: `<div v-once>child-two</div>`
});
var vm = new Vue({
el: "#root",
data: {
type: "child-one"
},
methods: {
handleButtonClick: function() {
this.type = (this.type == "child-one" ? "child-two" : "child-one");
}
}
})
</script>
</body>
</html>