vue基礎 動態元件 實現相互切換並快取資料
阿新 • • 發佈:2022-03-03
動態元件
準備工作
元件1:Acomponent
內容部分:
<template> <div>{{msg}}</div> </template> <script> export default { name:"Dynamic", data() { return { msg:"welcome 元件A!" } }, } </script>
元件2:Bcomponent
內容部分:
<template> <div>{{msg}}<button @click="ChangeContent">修改b的內容</button> </div> </template> <script> // import func from 'vue-editor-bridge' export default { name:"Dynamic", data() { return { msg:"welcome 元件B!" } }, methods:{ ChangeContent:function(){this.msg="被修改後的資料" } } } </script>
元件相互切換,
子元件引用AComponent、BComponent
<template> <div> 動態元件: <button @click="Adyc">A元件</button> <button @click="Bdyc">B元件</button> <!-- 元件相互切換並實現修改後快取 --> <keep-alive> <component v-bind:is="currentTabComponent"></component> </keep-alive>
<!-- 元件相互切換,但不會快取資料 --> <!-- <component v-bind:is="currentTabComponent"></component> --> </div> </template> <script> import Adynamic from "./AComponent" import Bdynamic from "./BComponent" export default { name:"Dynamic", data() { return { msg:"welcome DynamicDemo!", currentTabComponent:AComponent } }, components:{ Acomponent, Bcomponent }, methods:{ Adyc:function(){ this.currentTabComponent=AComponent }, Bdyc:function(){ this.currentTabComponent=BComponent } } } </script>
父元件:
<template> <div> <MyComponent/> </div> </template> <script> import HelloWorld from './components/HelloWorld' import Dynamic from './components/MyComponent.vue' export default { name: 'App', components: { HelloWorld, MyComponent } } </script> <style> #app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } </style>