vue.js组件

组件基础

基本实例

组件是带有名称的可复用实例,在这个例子中是 <button-counter>。我们可以把这个组件作为一个根实例中的自定义元素来使用

在页面上会有点击之后,数字加1的按钮

  <div id="components-demo">
    <button-counter></button-counter>
  </div>  
  <script>
  // 创建一个Vue 应用
  const app = Vue.createApp({})

  // 定义一个名为 button-counter 的新全局组件
  app.component('button-counter', {
    data() {
      return {
        count: 0
      }
    },
    template: `
      <button @click="count++">
        You clicked me {{ count }} times.
      </button>`
  })
  app.mount('#components-demo')
  </script>
复用组件

在以下示例中,页面会有三个不同的独立button-counter组件

<div id="components-demo">
  <button-counter></button-counter>
  <button-counter></button-counter>
  <button-counter></button-counter>
</div>
通过 Prop 向子组件传递数据

你不能向这个组件传递某一篇博文的标题或内容之类的我们想展示的数据的话,它是没有办法使用的。这也正是 prop 的由来。

  <div id="blog-post-demo">
    <blog-post title="my blog"></blog-post>
  </div>  
  <script>
  // 创建一个Vue 应用
  const app = Vue.createApp({})

  // 定义一个名为 blog-post 的新全局组件
  app.component('blog-post', {
    props: ['title'],
    template: `<h4>{{ title }}</h4>`
  })

  app.mount('#blog-post-demo')
  </script>

然而在一个典型的应用中,你可能在 data 里有一个博文的数组

使用 v-bind 来动态传递 prop。这在一开始不清楚要渲染的具体内容,是非常有用的。

  <div id="blog-post-demo">
    <blog-post v-for="post in posts" :key="post.id" :title="post.title"></blog-post>
  </div>  
  <script>
  const App={
    data(){
      return {
        posts: [
          {id:1,title:'my blog'},
          {id:2,title:'blog theme is vue'}
        ]
      }
    }
  }
  // 创建一个Vue 应用
  const app = Vue.createApp(App)

  // 定义一个名为 blog-post 的新全局组件
  app.component('blog-post', {
    props: ['title'],
    template: `<h4>{{ title }}</h4>`
  })

  app.mount('#blog-post-demo')
  </script>
监听组件事件

我们在开发 <blog-post> 组件时,它的一些功能可能需要与父级组件进行沟通。例如我们可能会引入一个辅助功能来放大博文的字号,同时让页面的其它部分保持默认的字号。

父级组件可以像处理 native DOM 事件一样通过 v-on 监听子组件实例的任意事件

同时子组件可以通过调用内建的 $emit 方法并传入事件名称来触发一个事件

  <div id="blog-posts-events-demo">
    <div :style="{ fontSize: postFontSize + 'em' }">
      <blog-post
        v-for="post in posts"
        :key="post.id"
        :title="post.title"
        @enlarge-text="postFontSize += 0.1"
      ></blog-post>
    </div>
  </div>
  <script>
  const App={
    data(){
      return {
        posts: [
          {id:1,title:'my blog'},
          {id:2,title:'blog theme is vue'}
        ],
        postFontSize: 1
      }
    }
  }
  // 创建一个Vue 应用
  const app = Vue.createApp(App)

  // 定义一个名为 blog-post 的新全局组件
  app.component('blog-post', {
    props: ['title'],
    template: `    
    <div class="blog-post">
      <h4>{{ title }}</h4>
      <button @click="$emit('enlarge-text')">
        Enlarge text
      </button>
    </div>`
  })

  app.mount('#blog-posts-events-demo')
  </script>
使用事件抛出一个值

如果要让 <blog-post> 组件决定它的文本要放大多少。这时可以使用 $emit 的第二个参数来提供这个值

<button @click="$emit('enlargeText', 0.1)">
  Enlarge text
</button>

然后当在父级组件监听这个事件的时候,我们可以通过 $event 访问到被抛出的这个值

<blog-post ... @enlarge-text="postFontSize += $event"></blog-post><blog-post ... @enlarge-text="onEnlargeText"></blog-post>

如果要触发这个方法,那么必须定义

methods: {
  onEnlargeText: function (enlargeAmount) {
    this.postFontSize += enlargeAmount
  }
}
在组件上使用 v-model
  <div id="app">
    <custom-input v-model="searchText"></custom-input>
  </div>  
  <script>
  // 创建一个Vue 应用
  const app = Vue.createApp({})

 
  app.component('custom-input', {
  props: ['value'],
  template: `
    <input
      v-bind:value="value"
      v-on:input="$emit('input', $event.target.value)"
    >
  `
  })
  app.mount('#app')
  </script>

在这里插入图片描述

插槽

以下代码,slot元素被替换为了字符串Something had happened

  <div id="app">
    <alert-box>
      Something bad happened.
    </alert-box>
  </div>  
  <script>
  // 创建一个Vue 应用
  const app = Vue.createApp({})
  
  app.component('alert-box', {
  template: `
    <div class="demo-alert-box">
      <strong>Error!</strong>
      <slot></slot>
    </div>
  `
  })
  app.mount('#app')
  </script>
动态组件

官方文档示例

<!DOCTYPE html>
<html>
  <head>
    <title>Vue Component Blog Post Example</title>
    <script src="https://unpkg.com/vue"></script>
    <link rel="stylesheet" type="text/css" href="style.css" />
  </head>
  <body>
    <div id="dynamic-component-demo">
      <button
        v-for="tab in tabs"
        v-bind:key="tab"
        v-bind:class="['tab-button', { active: currentTab === tab }]"
        v-on:click="currentTab = tab"
      >
        {{ tab }}
      </button>

      <keep-alive>
        <component v-bind:is="currentTabComponent" class="tab"></component>
      </keep-alive>
    </div>

    <script>
      Vue.component("tab-posts", {
        data: function() {
          return {
            posts: [
              {
                id: 1,
                title: "Cat Ipsum",
                content:
                  "<p>Dont wait for the storm to pass, dance in the rain kick up litter decide to want nothing to do with my owner today demand to be let outside at once, and expect owner to wait for me as i think about it cat cat moo moo lick ears lick paws so make meme, make cute face but lick the other cats. Kitty poochy chase imaginary bugs, but stand in front of the computer screen. Sweet beast cat dog hate mouse eat string barf pillow no baths hate everything stare at guinea pigs. My left donut is missing, as is my right loved it, hated it, loved it, hated it scoot butt on the rug cat not kitten around</p>"
              },
              {
                id: 2,
                title: "Hipster Ipsum",
                content:
                  "<p>Bushwick blue bottle scenester helvetica ugh, meh four loko. Put a bird on it lumbersexual franzen shabby chic, street art knausgaard trust fund shaman scenester live-edge mixtape taxidermy viral yuccie succulents. Keytar poke bicycle rights, crucifix street art neutra air plant PBR&B hoodie plaid venmo. Tilde swag art party fanny pack vinyl letterpress venmo jean shorts offal mumblecore. Vice blog gentrify mlkshk tattooed occupy snackwave, hoodie craft beer next level migas 8-bit chartreuse. Trust fund food truck drinking vinegar gochujang.</p>"
              },
              {
                id: 3,
                title: "Cupcake Ipsum",
                content:
                  "<p>Icing dessert soufflé lollipop chocolate bar sweet tart cake chupa chups. Soufflé marzipan jelly beans croissant toffee marzipan cupcake icing fruitcake. Muffin cake pudding soufflé wafer jelly bear claw sesame snaps marshmallow. Marzipan soufflé croissant lemon drops gingerbread sugar plum lemon drops apple pie gummies. Sweet roll donut oat cake toffee cake. Liquorice candy macaroon toffee cookie marzipan.</p>"
              }
            ],
            selectedPost: null
          };
        },
        template: `
  	<div class="posts-tab">
      <ul class="posts-sidebar">
        <li
          v-for="post in posts"
          v-bind:key="post.id"
          v-bind:class="{ selected: post === selectedPost }"
					v-on:click="selectedPost = post"
        >
          {{ post.title }}
        </li>
      </ul>
      <div class="selected-post-container">
      	<div 
        	v-if="selectedPost"
          class="selected-post"
        >
          <h3>{{ selectedPost.title }}</h3>
          <div v-html="selectedPost.content"></div>
        </div>
        <strong v-else>
          Click on a blog title to the left to view it.
        </strong>
      </div>
    </div>
  `
      });

      Vue.component("tab-archive", {
        template: "<div>Archive component</div>"
      });

      new Vue({
        el: "#dynamic-component-demo",
        data: {
          currentTab: "Posts",
          tabs: ["Posts", "Archive"]
        },
        computed: {
          currentTabComponent: function() {
            return "tab-" + this.currentTab.toLowerCase();
          }
        }
      });
    </script>
  </body>
</html>
.tab-button {
  padding: 6px 10px;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
  border: 1px solid #ccc;
  cursor: pointer;
  background: #f0f0f0;
  margin-bottom: -1px;
  margin-right: -1px;
}
.tab-button:hover {
  background: #e0e0e0;
}
.tab-button.active {
  background: #e0e0e0;
}
.tab {
  border: 1px solid #ccc;
  padding: 10px;
}
.posts-tab {
  display: flex;
}
.posts-sidebar {
  max-width: 40vw;
  margin: 0;
  padding: 0 10px 0 0;
  list-style-type: none;
  border-right: 1px solid #ccc;
}
.posts-sidebar li {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  cursor: pointer;
}
.posts-sidebar li:hover {
  background: #eee;
}
.posts-sidebar li.selected {
  background: lightblue;
}
.selected-post-container {
  padding-left: 10px;
}
.selected-post > :first-child {
  margin-top: 0;
  padding-top: 0;
}

如果你选择了一篇文章,切换到 Archive 标签,然后再切换回 Posts,是不会继续展示你之前选择的文章的。这是因为你每次切换新标签的时候,Vue 都创建了一个新的 currentTabComponent 实例。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值