这是第一种写法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
</body>
<script>
const app = Vue.createApp({
data() {
return {
isShow: false,
};
},
methods: {
handleClick() {
this.isShow = !this.isShow;
},
},
template: `
<welcome v-if="isShow"/>
<goodby v-else />
<button @click="handleClick">切换</button>
`,
});
app.component("welcome", {
template: `
<h1>我是welcome组件</h1>
`,
});
app.component("goodby", {
template: `
<h1>我是goodby组件</h1>
`,
});
const vm = app.mount("#root");
</script>
</html>
这是第二种写法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://unpkg.com/vue@next"></script>
</head>
<body>
<div id="root"></div>
</body>
<script>
const app = Vue.createApp({
data() {
return {
currentComponent: "welcome",
};
},
methods: {
handleClick() {
if (this.currentComponent === "welcome") {
this.currentComponent = "goodby";
} else {
this.currentComponent = "welcome";
}
},
},
template: `
<transition>
<component :is="currentComponent" />
</transition>
<button @click="handleClick">切换</button>
`,
});
app.component("welcome", {
template: `
<h1>我是welcome组件</h1>
`,
});
app.component("goodby", {
template: `
<h1>我是goodby组件</h1>
`,
});
const vm = app.mount("#root");
</script>
</html>