1.gif

1.定义子组件

  1. //components/One.vue
  2. <template>
  3. <div>
  4. one
  5. </div>
  6. </template>
  7. <script>
  8. export default {
  9. }
  10. </script>
  11. <style scoped>
  12. </style>
  13. //components/Two.vue
  14. <template>
  15. <div>
  16. two
  17. </div>
  18. </template>
  19. <script>
  20. export default {
  21. }
  22. </script>
  23. <style scoped>
  24. </style>

2.引入组件和data关联

使用:is is后面跟的one,two要在data()中关联

  1. <template>
  2. <div>
  3. <button @click="handleToggle">toggle</button> //点击进行切换
  4. <component :is="isToggle?one:two"></component>
  5. </div>
  6. </template>
  7. <script>
  8. import One from "@/components/One.vue";
  9. import Two from '@/components/Two.vue'
  10. export default {
  11. data() {
  12. return {
  13. isToggle:false,
  14. one: "One",
  15. two:"Two"
  16. };
  17. },
  18. components: {
  19. One,
  20. Two
  21. },
  22. methods:{
  23. handleToggle(){
  24. this.isToggle = !this.isToggle
  25. }
  26. }
  27. };
  28. </script>