Vue学习笔记之组件基础

别来无恙 提交于 2020-01-20 20:49:33

组件基础

// 一个名 button-counter 的新

Vue.component('button-counter', {

  data: function () {

    return {

      count: 0

    }

  },

  template: '<button v-on:click="count++">You clicked me {{ count }} times.</button>'

})

 

组件是可复用的 Vue 实例,且带有一个名字所以它们与 new Vue 接收相同的选项,例如 datacomputedwatchmethods 以及生命周期子等。有的例外是像 el 这样根实例特有的选项new Vue({ el: '#components-demo' })

另外,一个件的 data 选项必须是一个函,因此每个例可以维护一份被返回象的独立的拷,如果 Vue 没有规则,点一个按就可能会影响到其它所有

1 Prop 向子传递数据(父子)

1

Vue.component('blog-post', {

  props: ['title'],

  template: '<h3>{{ title }}</h3>'

})

 

<blog-post title="My journey with Vue"></blog-post>

 

    例2

new Vue({

  el: '#blog-post-demo',

  data: {

    posts: [

      { id: 1, title: 'My journey with Vue' },

      { id: 2, title: 'Blogging with Vue' },

      { id: 3, title: 'Why Vue is so fun' }

    ]

  }

})

 

<blog-post

  v-for="post in posts"

  v-bind:key="post.id"

  v-bind:title="post.title"

></blog-post>

例3

的博文不只需要标题和内容,需要布日期、评论等等。每个相关的信息定一个 prop 得很麻所以是时候重构一下这个 <blog-post> 组件了,让它变成接受一个单独的 post prop

<blog-post

  v-for="post in posts"

  v-bind:key="post.id"

  v-bind:post="post"

></blog-post>

Vue.component('blog-post', {

  props: ['post'],

  template: `

    <div class="blog-post">

      <h3>{{ post.title }}</h3>

      <div v-html="post.content"></div>

    </div>

  `

})

 

时为 post 对象添加一个新的属性,它都会自动地在 <blog-post> 内可用。

 

2 听子件事件(子——父

        Vue 实例提供了一个自定义事件的系统来解决这个问题。父级组件可以像处理 native DOM 事件一 v-on 监听子组件实例的任意事件。同件可以通过调用内建的 $emit 方法 入事件名称来触一个事件。

   (子)

Vue.component('blog-post', {

  props: ['post'],

  template: `

    <div class="blog-post">

      <h3>{{ post.title }}</h3>

      <button v-on:click="$emit('enlarge-text', 0.1)">

        Enlarge text

      </button>

      <div v-html="post.content"></div>

    </div>

  `

})

   (父)

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

<blog-post

  ...

  v-on:enlarge-text="postFontSize += $event"

></blog-post>

或者,如果个事件理函数是一个方法:

<blog-post

  ...

  v-on:enlarge-text="onEnlargeText"

></blog-post>

那么这个值(子组件传出的值0.1)将会作为第一个参数传入这个方法:

methods: {

  onEnlargeText: function (enlargeAmount) {

    this.postFontSize += enlargeAmount

  }

}

参考官网   https://cn.vuejs.org/v2/guide/list.html  总结笔记

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!