Vue刨坑

vue常见问题

1.在自定义组件里,你可以像任何普通元素一样用v-for。eg1:

<my-component v-for="item in items"></my-component>

然而他不能自动传递数据到组件里,因为组件有自己独立的作用域。
这意味着不能并且不应该在子组件的模板内直接引用父组件的数据。可以使用 props 把数据传给子组件。
为了传递迭代数据到组件里,我们要用 props :

props基础示例

下面的代码定义了一个子组件my-component,在Vue实例中定义了data选项。eg2:

var vm = new Vue({
    el: '#app',
    data: {
        name: 'keepfool',
        age: 28
    },
    components: {
        'my-component': {
            template: '#myComponent',
            props: ['myName', 'myAge']
        }
    }
})

为了便于理解,你可以将这个Vue实例看作my-component的父组件。
如果我们想使父组件的数据,则必须先在子组件中定义props属性,也就是props: ['myName', 'myAge']这行代码。

定义子组件的HTML模板:

<template id="myComponent">
    <table>
        <tr>
            <th colspan="2">
            子组件数据
            </th>
        </tr>
        <tr>
            <td>my name</td>
            <td>{{ myName }}</td>
        </tr>
        <tr>
            <td>my age</td>
            <td>{{ myAge }}</td>
        </tr>
     </table>
</template>

将父组件数据通过已定义好的props属性传递给子组件:

<div id="app">
    <my-component v-bind:my-name="name" v-bind:my-age="age"></my-component>
</div>

在线例子:https://keepfool.github.io/vue-tutorials/02.Components/Part-1/basic-props.html
注意:在子组件中定义prop时,使用了camelCase命名法。由于HTML特性不区分大小写,camelCase的prop用于特性时,需要转为 kebab-case(短横线隔开)。例如,在prop中定义的myName,在用作特性时需要转换为my-name。

在eg1中,可更改为:

<my-component
  v-for="(item, index) in items"
  v-bind:item="item"
  v-bind:index="index">
</my-component>

自定义事件

父组件是使用 props 传递数据给子组件,但如果子组件要把数据传递回去,应该怎样做?那就是自定义事件!

使用v-on绑定自定义事件

每个 Vue 实例都实现了事件接口(Events interface),即:

  • 使用 $on(eventName) 监听事件
  • 使用 $emit(eventName) 触发事件

如此,我们可以这样来传递事件(定义了 2 个 button,可以发送 increment 事件给父组件触发 incrementTotal)。

<div id="counter-event-example">
  <p>{{ total }}</p>
  <button-counter v-on:increment="incrementTotal"></button-counter>
  <button-counter v-on:increment="incrementTotal"></button-counter>
</div>
Vue.component('button-counter', {
  template: '<button v-on:click="increment">{{ counter }}</button>',
  data: function () {
    return {
      counter: 0
    }
  },
  methods: {
    increment: function () {
      this.counter += 1
      console.log(this)
      console.log(1)
      this.$emit('increment')

    }
  },
})
new Vue({
  el: '#counter-event-example',
  data: {
    total: 0
  },
  methods: {
    incrementTotal: function () {
      console.log(this)
      console.log(2)
      this.total += 1
    }
  }
})

参考文章:http://www.cnblogs.com/jhj117/p/5634034.html

努力将自己的温暖带给身边的人!!!!!
原文地址:https://www.cnblogs.com/xiaoli52qd/p/6203078.html