vue动态组件选项卡示例

概念:
Vue 中提供有一个内置的组件叫做 component 。这个组件就是动态组件,它需要设置 is 属性。is 属性的值就是需要渲染的组件的名字
1. 引入vue链接:
vue链接:https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>

2.创建组件(三个选项需要做三个小组件)。

      Vue.component("home", {
        template: `
          <div>
            <h1>home</h1>
          </div>
        `,
      });
      Vue.component("list", {
        template: `
          <div>
            <h1>list</h1>
          </div>
        `,
      });

      Vue.component("about", {
        template: `
          <div>
            <h1>about</h1>
          </div>
        `,
      });

3.创建实例。

      var vm = new Vue({
      //实例的id:app
        el: "#app",
        //data的数据是为了模拟一个选中时用的数据
        data: {
          curPage: "home",
        },
      });

4.调用组件与插件。

    <div id="app">
    //这里的css是一个高亮的样式用了v-bind做了绑定与判断
    //@click自定义事件触发curPage赋值为home将根里的data的数据修改为home
      <button :class="{ active: curPage === 'home' }" @click="curPage = 'home'">
        home
      </button>
      <button :class="{ active: curPage === 'list' }" @click="curPage = 'list'">
        list
      </button>
      <button
        :class="{ active: curPage === 'about' }"
        @click="curPage = 'about'"
      >
        about
      </button>

      <hr />
		//<component is="组件名" ></component>
		//is 属性的值就是需要渲染的组件的名字用v-bind绑定
      <component :is="curPage"></component>
    </div>
发布了4 篇原创文章 · 获赞 47 · 访问量 332

猜你喜欢

转载自blog.csdn.net/weixin_45816830/article/details/105519697