Vue3.0学习笔记 三


前言

一、组件与父组件传递数据给子组件方式props

1、基本示例

这是Vue组件的示例:

// Create a Vue application
const app = Vue.createApp({
   })

// Define a new global component called button-counter
app.component('button-counter', {
   
  data() {
   
    return {
   
      count: 0
    }
  },
  template: `
    <button @click="count++">
      You clicked me {
    { count }} times.
    </button>`
})

在这里插入图片描述
点击一次:
在这里插入图片描述

组件是具有名称的可重用实例:在这种情况下为<button-counter>。我们可以将此组件用作根实例内的自定义元素:

<div id="components-demo">
  <button-counter></button-counter>
</div>
app.mount('#components-demo')

由于组件是可重复使用的情况下,他们接受相同的选项,根实例,例如datacomputedwatchmethods,和生命周期钩。唯一的例外是一些特定于root的选项,例如el

2、重用组件

组件可以根据需要重复使用多次:

<div id="components-demo">
  <button-counter></button-counter>
  <button-counter></button-counter>
  <button-counter></button-counter>
</div>

结果:
在这里插入图片描述
点击:
在这里插入图片描述

,单击按钮时,每个按钮都保持自己独立的count。这是因为每次使用组件时,都会创建该组件的新实例。

3、通过道具将数据传递给子组件

道具是可以在组件上注册的自定义属性。将值传递给prop属性时,它将成为该组件实例的属性。要将标题传递给我们的博客文章组件,我们可以使用以下props选项将其包括在该组件接受的道具列表中:

const app = Vue.createApp({
   })

app.component('blog-post', {
   
  props: ['title'],
  template: `<h4>{
    { title }}</h4>`
})

app.mount('#blog-post-demo')

一个组件可以具有任意数量的道具,并且默认情况下,任何值都可以传递给任何道具。在上面的模板中,您将看到我们可以像使用一样在组件实例上访问此值data

注册道具后,您可以将数据作为自定义属性传递给它,如下所示:

<div id="blog-post-demo" class="demo">
  <blog-post title="My journey with Vue"></blog-post>
  <blog-post title="Blogging with Vue"></blog-post>
  <blog-post title="Why Vue is so fun"></blog-post>
</div>

结果:
在这里插入图片描述

但是,在典型的应用中,您可能会在中发表一系列文章data

const App = {
   
  data() {
   
    return {
   
      posts: [
        {
    id: 1, title: 'My journey with Vue' },
        {
    id: 2, title: 'Blogging with Vue' },
        {
    id: 3, title: 'Why Vue is so fun' }
      ]
    }
  }
}

const app = Vue.createApp(
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值